繁体   English   中英

iOS核心动画:旋转的锚点不正确

[英]iOS Core Animation: incorrect anchor point for rotation

我想在iOS中实现基本旋转动画,其中视图围绕其中心点连续旋转。

但是,由于某种原因,旋转的锚点始终是父视图的原点,而不是旋转视图的中心。
因此,即使我手动设置锚点,视图也会围绕屏幕的左上角旋转。

这是我正在做的事情:

// 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"];

任何帮助,将不胜感激。

路径不定义图层的边界。 因此,您的图层具有CGRectZero边界。 您的路径从CGPointZero开始,相对于边界。 该层围绕其中心旋转,这也是CGPointZero ......

所以,我看到了几个选择:

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

要么:

layer.bounds = CGPathGetBoundingBox(layer.path);

我也遇到了同样的问题。 即使在手动设置为(0.5,0.5)之后,缩放和旋转似乎也在使用左上角的anchorPoint。 我通过手动设置图层的框架或边界属性将其固定在我的代码上,使其具有与路径相同的大小。

您可以使用UIView方法而不是图层方法。 它们默认围绕中心旋转。

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

以下是在不使用anchorPoint的情况下围绕特定点旋转的方法。 我不确定anchorPoint应该为旋转动画做什么,但它似乎没有做你想要的。

“First”翻译,因此您的旋转中心位于原点。 因此,请向左和向上应用翻译。

然后旋转。

然后转换回所需的位置。 因此,应用正确和向下的翻译。

您可以通过连接矩阵同时执行这些操作。 它们的顺序相反。 从左到右:右/下翻译,旋转,左/上翻译。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM