我希望使用 Core Animation 在 Mac 应用程序中模拟翻转时钟动画。目前我有三个 CALayer 代表数字的上半部分和下半部分,第三个用于代表翻转动画(在以下文章中找到了解决方案:使用 Core Animation 创建 iPad 翻转时钟 http://www.voyce.com/index.php/2010/04/10/creating-an-ipad-flip-clock-with-core-animation/.
翻转层的动画分为两个阶段:从数字顶部翻转到数字中间,然后从中间翻转到底部。为了实现这一点,我使用了一个委托函数,每当动画结束时就会调用该函数:
- (void)animationDidStop:(CAAnimation *)oldAnimation finished:(BOOL)flag
{
int digitIndex = [[oldAnimation valueForKey:@"digit"] intValue];
int currentValue = [[oldAnimation valueForKey:@"value"] intValue];
NSMutableArray *digit = [digits objectAtIndex:digitIndex];
CALayer *flipLayer = [digit objectAtIndex:tickerFlip];
CALayer *bottomLayer = [digit objectAtIndex:tickerBottom];
if([[oldAnimation valueForKey:@"state"] isEqual:@"top"] && flag) {
NSLog(@"Top animation finished");
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
flipLayer.contents = [bottomImages objectAtIndex:currentValue];
flipLayer.anchorPoint = CGPointMake(0.0, 1.0);
flipLayer.hidden = NO;
[CATransaction commit];
CABasicAnimation *anim = [self generateAnimationForState:@"bottom"];
[anim setValue:[NSString stringWithFormat:@"%d", digitIndex] forKey:@"digit"];
[anim setValue:[NSString stringWithFormat:@"%d", currentValue] forKey:@"value"];
[flipLayer addAnimation:anim forKey:nil];
} else if([[oldAnimation valueForKey:@"state"] isEqual:@"bottom"] && flag) {
NSLog(@"Bottom animation finished");
// Hide our flip layer
[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
bottomLayer.contents = [bottomImages objectAtIndex:currentValue];
flipLayer.hidden = YES;
flipLayer.anchorPoint = CGPointMake(0.0, 0.0);
[CATransaction commit];
}
}
此委托函数使用辅助函数,该函数根据翻转层的状态生成翻转层的变换:
- (CABasicAnimation *)generateAnimationForState:(NSString *)state
{
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform"];
anim.duration = 0.15;
anim.repeatCount = 1;
// Check which animation we're doing
if([state isEqualToString:@"top"])
{
anim.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.0f, 1, 0, 0)];
anim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI/2, 1, 0, 0)];
}
else
{
anim.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(-M_PI/2, 1, 0, 0)];
anim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0.0f, 1, 0, 0)];
}
anim.delegate = self;
anim.removedOnCompletion = NO;
// Set our animations state
[anim setValue:state forKey:@"state"];
return anim;
}
此解决方案有效,但在动画进行时会导致一些轻微的闪烁。我相信这是由于我的翻转层在“顶部”和“底部”动画之间重置的转换造成的。需要注意的是,在动画的第一阶段完成后,我将翻转图层锚点设置到图像的顶部,以确保翻转枢轴正确。
目前我不确定我的动画是否已设置最佳。总的来说,我对转换和核心动画很陌生。有人能指出我正确的方向吗?