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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With