What is the AnchorPoint of a CALayer?
AnchorPoint of a CALayer is an important property if you want to do any kind of geometrical transformation on that layer. Read the official documentation.
According to Apple: anchorPoint “defines the anchor point of the layer’s bounds rectangle.”
It is a CGPoint. Its x and y values are represented in unit coordinates, from 0 to 1 or -1 to 0 and so on.
The image above shows a CALayer’s anchor points.
- (0,0) is top left
- (1,0) is top right
- (0.5,0.5) is center (default)
- (0,1) is bottom left
- (1,0) is bottom right
(0.5,0.5) is the default anchor point of a CALayer. Like the above values, the anchor point can also be outside of a CALayer.
If we change the anchorPoint of a CALayer, and then apply any geometric transformation, it’ll transform according to the point.
Here’s an example:
Here is an example of a layer rotation animation. The CALayer’s anchorPoint hasn’t been changed, so it is (0.5,0.5) the centre of the layer. We can see, that the layer rotates around the centre, make sense.
Now, let’s change the anchor point and try the same thing.
This time the layer’s anchorPoint has been changed to (0,0) the top left. We can see that the layer now rotates around the top left point. Just make to set the anchorPoint before you set the frame of your layer.