Frame and Bounds of CAShapeLayer

h999 picture h999 · Sep 23, 2013 · Viewed 13.5k times · Source

I am working on CAShapeLayer.And trying to draw non-linear path.I want to set frame to CAShapeLayer.So i can use CGPathGetPathBoundingBox method to get frame from CGPathRef.

Here is code :

CGMutablePathRef path = CGPathCreateMutable();
CGPathAddArc(path, NULL, rect.size.width/2, rect.size.height/2, 100, (0), (M_PI_2), NO);
CGPathAddArc(path, NULL, rect.size.width/2, rect.size.height/2, 100-50, (M_PI_2), (0), YES);
CGPathCloseSubpath(path);
CAShapeLayer* arcLayer = [[CAShapeLayer alloc]init];
arcLayer.path = path;
arcLayer.frame = CGPathGetPathBoundingBox(path);
arcLayer.bounds = CGPathGetPathBoundingBox(path);
[self.layer addSublayer:arcLayer]; ` 

Please refer my code carefully .I have set same frame and bounds to CAShapeLayer.My problem is if i am not setting bounds (same as frame) ,then it wont show my content or it wont show my content within frame.Why?Please help me.Thanking you.

Answer

Tungsten picture Tungsten · Dec 30, 2013

When you modify the frame of a CALayer, you are modifying its size and position in the coordinate space of its superlayer. frame is a computed value, based on the object's bounds and position. In this case, the layer does not yet have a superlayer so its coordinate space is dimensionless. When you set the frame, the size gets carried through to the bounds property, but since any point in a dimensionless space is zero, the position will remain zero instead of what you'd intended.

To solve this, you can set the bounds to set the layer's size, and position (which is a real non-computed property) in the coordinate space of the superlayer before adding it as a sublayer.