如何围绕其中心旋转UIView,持续时间为1分钟,间隔为1秒,动画如丝般顺滑?

时间:2013-08-03 23:20:43

标签: ios objective-c uiviewanimation

我试图旋转UIView。这个UIView代表一个时钟的秒指针。

我需要每秒更新一次。像这样:

- (void)startUpdates {
    _updateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(animatePointer) userInfo:nil repeats:YES];
}

当我需要它时停止它,就像这样:

- (void)stopUpdates {
    [_updateTimer invalidate];
    _updateTimer = nil;
}

每秒钟动画,从一秒到下一秒,就像这样:

- (void)animatePointer {

    NSDate *now = [NSDate date];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSSecondCalendarUnit fromDate:now];

    float angleForSeconds = (float)[components second] / 60.0;

    [UIView animateWithDuration:1.0 animations:^(void){
        _pointerGlow.layer.transform = CATransform3DMakeRotation((M_PI * 2) * angleForSeconds, 0, 0, 1);
    }];

}

这确实有效,但并不顺利。它每秒停止一秒钟,就像一个典型的挂钟。很好,但不是我想要的。

有什么方法可以让这个动画如丝般顺畅吗?

1 个答案:

答案 0 :(得分:1)

您可以使用与显示刷新率60 /秒相关联的CADisplayLink进行尝试。代码看起来像这样(请注意,我没有添加任何逻辑来停止显示链接,但是如果你愿意,我会调用你可以调用的方法):

#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface ViewController ()
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic) CFTimeInterval firstTimestamp;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self startDisplayLink];
}


- (void)startDisplayLink {
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
    [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)stopDisplayLink {
    [self.displayLink invalidate];
    self.displayLink = nil;
}

- (void)handleDisplayLink:(CADisplayLink *)displayLink {
    if (!self.firstTimestamp) self.firstTimestamp = displayLink.timestamp;
    NSTimeInterval elapsed = (displayLink.timestamp - self.firstTimestamp);
    self.arrow.layer.transform = CATransform3DMakeRotation((M_PI * 2) * elapsed/60, 0, 0, 1);
}