项目的任务,需要实现一个类似于下图的翻转动画,图片在翻转的同时,还要进行改变。

ed451596a4e1?tdsourcetag=s_pcqq_aiomsg

目标动画

最开始,直接使用UIView的动画。

代码很简单:- (void)viewAnimation {

[UIView transitionWithView:_imageView duration:2*actionSeconds options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{

if (_imageView.tag == 101) {

_imageView.image = [UIImage imageNamed:@"logo"];

_imageView.tag = 102;

} else {

_imageView.image = [UIImage imageNamed:@"icon"];

_imageView.tag = 101;

}

}completion:^(BOOL finished) {

[self viewAnimation];

}];

}

但是,这样实现的动画,图片在翻转的时候,背景会变暗。

ed451596a4e1?tdsourcetag=s_pcqq_aiomsg

view动画

这是因为,在翻转的时候,imageView的alpha值会变化。

为了图片背景不变暗,所以决定使用layer层的动画。

代码如下:- (void)simpleLyerRotation

{

CABasicAnimation* basicAnimation;

basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.y"];

basicAnimation.toValue = [NSNumber numberWithFloat: M_PI ];

basicAnimation.duration = 1.2*actionSeconds;

basicAnimation.cumulative = NO;

basicAnimation.repeatCount = 1;

basicAnimation.fillMode = kCAFillModeForwards;

basicAnimation.removedOnCompletion = NO;

basicAnimation.delegate = self;

[_imageView.layer addAnimation:basicAnimation forKey:@"rotationAnimation"];

[self performSelector:@selector(changeImg) withObject:nil afterDelay:0.6 * actionSeconds];

}- (void)changeImg

{

if (_imageView.tag == 101) {

_imageView.image = [UIImage imageNamed:@"logo"];

_imageView.tag = 102;

} else {

_imageView.image = [UIImage imageNamed:@"icon"];

_imageView.tag = 101;

}

}

但是,效果有问题,翻转的时候,会转到反面去。

ed451596a4e1?tdsourcetag=s_pcqq_aiomsg

简单layer动画

仔细分析之后,我发现,需要达到的功能是:图片先顺着旋转90°,接着再逆着旋转90°。这样,就不会显示反着的图片。

这样的话,就需要一个连续的动画效果。

使用CABasicAnimation,我无法实现这样的功能。后来,发现可以使用CAKeyframeAnimation,来创建这样的动画效果。

代码如下:- (void)layerRotation  {

CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animation];

// 旋转角度, 其中的value表示图像旋转的最终位置

keyAnimation.values = [NSArray arrayWithObjects:

[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0, 0,1,0)],

[NSValue valueWithCATransform3D:CATransform3DMakeRotation((M_PI/2), 0,1,0)],

[NSValue valueWithCATransform3D:CATransform3DMakeRotation(0, 0,1,0)],

nil];

keyAnimation.cumulative = NO;

keyAnimation.duration = 1.2 * actionSeconds;

keyAnimation.repeatCount = 1;

keyAnimation.removedOnCompletion = NO;

keyAnimation.delegate = self;

[_imageView.layer addAnimation:keyAnimation forKey:@"transform"];

[self performSelector:@selector(changeImg) withObject:nil afterDelay:0.6 * actionSeconds];

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐