I would like to implement a basic rotation animation in iOS, where the view is continuously rotating around its center point.
However, for some reason, the rotation's anchor point is always the parent view's origin, and not the rotating view's center.
Therefore, the view is rotating around the upper left corner of the screen, even if I manually set the anchor point.
Here's what I'm doing:
// Add shape layer to view
CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
CGRect shapeRect = CGRectMake(0, 0, 100, 100);
UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:shapeRect cornerRadius:5];
shapeLayer.path = roundedRect.CGPath;
shapeLayer.anchorPoint = CGPointMake(0.5, 0.5);
shapeLayer.fillColor = [[UIColor redColor] CGColor];
[self.view.layer addSublayer:shapeLayer];
// Set rotation animation
CATransform3D rotationTransform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
rotationAnimation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
rotationAnimation.duration = 1.0f;
rotationAnimation.cumulative = YES;
rotationAnimation.repeatCount = HUGE_VALF;
[shapeLayer addAnimation:rotationAnimation forKey:@"transform"];
Any help would be appreciated.
The path does not define layer's bounds. So, your layer has CGRectZero
bounds. Your path starts at CGPointZero
relative to the bounds. The layer is rotated around its center, which is also CGPointZero
...
So, I see several options:
layer.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(-50, -50,
100, 100)
cornerRadius:5].CGPath;
Or:
layer.bounds = CGPathGetBoundingBox(layer.path);
I also encountered the same problem. Scaling and rotation seems to be using a top-left anchorPoint even after setting it manually to (0.5, 0.5). I fixed it on my code by manually setting the layer's frame or bounds property to have the same size as your path.
You can just use UIView methods instead of layer methods. They rotate around the center by default.
[UIView beginAnimations];
self.view.transform = CGAffineTransformMakeRotation(M_PI);
[UIView commitAnimations];
Here is how you can rotate around a particular point, without using anchorPoint. I'm not sure what anchorPoint is supposed to do for a rotation animation, but it doesn't seem to be doing what you want.
"First" translate so your center of rotation is at the origin. So apply a translation left and up.
Then rotate.
Then translate back to the desired position. So apply a translation right and down.
You do those simultaneously by concatenating the matrices. They go in reverse order. From left to right: the right/down translation, the rotation, the left/up translation.