Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Core Animation: incorrect anchor point for rotation

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.

like image 820
antalkerekes Avatar asked Nov 15 '11 21:11

antalkerekes


2 Answers

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);
like image 151
debleek63 Avatar answered Oct 19 '22 23:10

debleek63


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.

like image 37
Lino Avatar answered Oct 19 '22 22:10

Lino