IOS Core Animation: Wrong reference point for rotation

I would like to implement basic rotation animation in iOS, where the view rotates continuously around its center point.

However, for some reason, the pivot point is always the original view of the parent view, and not the rotating view center.
Thus, the view rotates around the upper left corner of the screen, even if I manually set the anchor point.

That'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.

+4
source share
4 answers

The path does not define the boundaries of the layers. Thus, your layer has the borders of CGRectZero . Your journey begins with CGPointZero relative to the borders. The layer revolves around its center, as well as CGPointZero ...

So, I see several options:

 layer.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(-50, -50, 100, 100) cornerRadius:5].CGPath; 

Or:

 layer.bounds = CGPathGetBoundingBox(layer.path); 
+15
source

I also ran into the same problem. Scaling and rotation seem to use the top left anchorPoint even after manually setting it (0.5, 0.5). I fixed it in my code by manually setting the bounds for this layer or border to be the same size as your path.

+3
source

You can use UIView methods instead of layer methods. By default, they rotate around the center.

 [UIView beginAnimations]; self.view.transform = CGAffineTransformMakeRotation(M_PI); [UIView commitAnimations]; 
0
source

Here's how you can rotate around a specific point without using anchorPoint. I'm not sure what the anchor should do for the rotation animation, but it doesn't seem to do what you need.

First, translate so that your center of rotation is at the origin. Therefore, apply the translation left and up.

Then turn.

Then move back to the desired position. Therefore, apply the translation on the right and down.

You do this simultaneously by concatenating matrices. They go in reverse order. From left to right: translate right / down, rotate, shift left / up.

0
source

Source: https://habr.com/ru/post/1381384/


All Articles