使用Core Animation Framework进行平滑的摆动动画

时间:2010-02-06 22:51:14

标签: iphone objective-c animation core-animation

我试图用uiimageview做动画。 在这个视图中是一个带箭头的图像,我想要像摆动或旧时钟一样非常平滑地向后和向前旋转45度。 像这样的东西,只是平滑和我的形象:http://bit.ly/cArvNw(发现这与谷歌;))

我目前的设置如下:

    UIImageView* rotatingImage = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 10.0, 200.0, 200.0)];
    [rotatingImage setImage:[UIImage imageNamed:@"wind.png"]];

    CALayer *layer = rotatingImage.layer;
    CAKeyframeAnimation *animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.duration = 0.5f;
    animation.cumulative = YES;
    animation.repeatCount = 100;
    animation.values = [NSArray arrayWithObjects:           // i.e., Rotation values for the 3 keyframes, in RADIANS
                        [NSNumber numberWithFloat:[self degreesToRadians:45.0]], 
                        [NSNumber numberWithFloat:[self degreesToRadians:-45.0]], nil]; 
    animation.keyTimes = [NSArray arrayWithObjects:     // Relative timing values for the 3 keyframes
                          [NSNumber numberWithFloat:0], 
                          [NSNumber numberWithFloat:.5], nil]; 
    animation.timingFunctions = [NSArray arrayWithObjects:
                                 [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn],        // from keyframe 1 to keyframe 2
                                 [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut], nil]; // from keyframe 2 to keyframe 3
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;

    [layer addAnimation:animation forKey:nil];

    [self addSubview:rotatingImage];

这真是一种痛苦,加45度,然后向后45度,“-45”不起作用。 我是核心动画的新手,不知道如何设置我的代码,以获得我想要的动画。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

您是否看过Apple的示例iPhone应用程序“Metronome”?

使用Core Animation,它几乎完全符合您的要求。

答案 1 :(得分:1)

注意:此方法不使用Core Animation,但它非常简单,可能使用的资源更少。

首先,使UIImageView高两倍,从而使旋转中心等于图像的中心。

然后,在头文件的@interface中定义它们(例如,你的UIViewController):

BOOL goingCW; // going clockwise = YES, going counterclockwise = NO
CGFloat angle; // angle by which to change the image's rotation value

然后将它放在运行一次的init方法中:

goingCW = YES; // change this to NO to make it start rotating CCW instead
angle = 0;

[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(update) userInfo:nil repeats:YES];

然后定义update,假设arrow是UIImageView实例:

- (void)update {
    if (goingCW) {
        if (angle > M_PI / 4) goingCW = NO; // M_PI / 4 is equal to 45 degrees
        angle += M_PI / 60; // increase 60 to slow down the rotation, etc.
    } else {
        if (angle < -M_PI / 4) goingCW = YES; // -M_PI / 4 is equal to -45 degrees
        angle -= M_PI / 60; // increase 60 to slow down the rotation, etc.
    }

    // rotate the UIImageView appropriately
    arrow.transform = CGAffineTransformMakeRotation(angle);
}

这也假设您从面朝下的位置开始。