iPhone UIImageView 旋转

8

有人能告诉我如何使图像以圆形运动旋转吗?

5个回答

28

您可以旋转视图,旋转的角度可以少于一整个旋转或多个完整旋转的倍数,而无需将旋转拆分成几部分。例如,以下代码将使视图在指定秒数内每秒旋转一次。您可以轻松修改它以使视图旋转特定数量的旋转或某些弧度。

- (void) runSpinAnimationWithDuration:(CGFloat) duration;
{
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 /* full rotation*/ * rotations * duration ];
    rotationAnimation.duration = duration;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 1.0; 
    rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

    [myView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

我遇到一个错误,"rotations未声明"。 - abhinav
3
旋转次数是常量。请用您想要视图在持续时间内旋转的次数来替换它。 - mahboudz
我不是程序。 - Kevin ABRIOUX

3

根据mahboudz的回答,您可以将其设置为无限旋转,方法如下:
rotationAnimation.repeatCount = HUGE_VALF;


2
如果你的意思是“如何让图片沿着圆形路径运动?”,那么伪代码应该如下所示:
image.x = circleCentre.x + cos(angle) * circleRadius;
image.y = circleCentre.y + sin(angle) * circleRadius;
angle += 5;

1
创建动画
- (CABasicAnimation *)spinAnimationWithDuration:(CGFloat)duration clockwise:(BOOL)clockwise repeat:(BOOL)repeats
{
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    anim.toValue = clockwise ? @(M_PI * 2.0) : @(M_PI * -2.0);
    anim.duration = duration;
    anim.cumulative = YES;
    anim.repeatCount = repeats ? CGFLOAT_MAX : 0;
    return anim;
}

将它添加到视图中。
CABasicAnimation *animation = [self spinAnimationWithDuration:1.0 clockwise:YES repeat:YES];
[self.spinningView.layer addAnimation:animation forKey:@"rotationAnimation"];

这个答案和@mahboudz的答案有什么不同?如果大多数函数返回对象而不是仅在此处和那里操作某些对象,则代码将更加清晰。

1

这个问题提出了同样的问题,只是用不同的话表达。那个问题的答案以及这个问题中的答案应该可以提供一种方法来使一个UIView(UIImageView只是它的子类)绕其中心旋转360度或更多。


你可能对旋转和革命感到困惑。上述问题是关于革命的。 - Biranchi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接