iOS核心动画:旋转的锚点不正确 [英] iOS Core Animation: incorrect anchor point for rotation

查看:723
本文介绍了iOS核心动画:旋转的锚点不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是,出于某种原因,旋转的锚点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.

推荐答案

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

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;

或者:

layer.bounds = CGPathGetBoundingBox(layer.path);

这篇关于iOS核心动画:旋转的锚点不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆