views:

1890

answers:

4

How can I rotate a layer using Core Animation around an arbitrary point? ( In my case a point that is not inside the layer I want to rotate )

I prefer doing this without changing the anchor point, because unless I get something wrong every time I change the anchor point it also changes the position of the layer.

I tried something like that but it didn't work:

[UIImageView beginAnimations:nil context:nil];
CATransform3D rotationTransform = CATransform3DIdentity;
rotationTransform = CATransform3DTranslate(rotationTransform, 0.0, -100.0, 0.0);
rotationTransform = CATransform3DRotate(rotationTransform, DegreesToRadians(180),
                        0.0, 0.0, 1.0);
rotationTransform = CATransform3DTranslate(rotationTransform, 0.0, 100.0, 0.0)
shape1.layer.transform = rotationTransform;
[UIImageView commitAnimations];

It looks like the rotation axis is moving during the rotate.

+2  A: 

You can do this by appending multiple transformations:

  1. translate the layer by (-rotCenterX, rotCenterY)
  2. rotate the layer
  3. translate the layer by (rotCenterX, rotCenterY)
lajos
A: 

I finaly did it by creating a new bigger layer with it's center at my rotation axis and setting the layer i want to rotate as it's sub layer.

Then I rotate the bigger layer instead of the sub layer

Gu1234
While this may work for your specific case, it is not a general solution, in that it can fail if the desired rotation pushes the container-layer beyond the layer-size limits.Anchor points are really what you need, here.
Olie
+3  A: 

Hi gu,

Your solution is fine but the 'expected way' is to use the anchor point.

It is moving around when you set the anchor point because the position is attached to the anchor point, i.e. setting the position sets where the anchorPoint is in the superlayer's coord system.

Probably not worth changing since you have something working, but just something to add to the grey matter for next time.

Good luck!

Bill Dudney
A: 

Your initial solution is not fine as the translation is animated just like the rotation is. So the "custom-center" of your rotation is moving during the rotation. What you actually want is a translation without animation and the rotation with the animation based on that non-animated translation. Thing is, I currently have the exact same problem and couldnt come up with a solution yet. I am looking at CATransaction at the moment, hoping that could be the key...

Till