图片轮播展示完毕的切换卡顿,哪可能逃过产品Dog(就说了能咋地?)的法眼。下面才是入坑的开始:思路是两张一样的图片并排排列,首尾相连,同时左移,设置相同动画时间,X值不断减小,动画结束回调Frame重置方法,递归回调
#import "HCNewLoginViewControllerJJ.h"
#import "MoveAnimationView.h"
@interface HCNewLoginViewControllerJJ ()
@end
@implementation HCNewLoginViewControllerJJ
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self startMoveAnimation];
}
- (void)startMoveAnimation {
UIImage *bgImg = [UIImage imageNamed:@"loginvideoee"];
CGFloat width = 1.f * bgImg.size.width / bgImg.size.height * kScreenHeight;
UIImageView *bgImgV_1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
bgImgV_1.image = bgImg;
UIImageView *bgImgV_2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight)];
bgImgV_2.image = [UIImage imageNamed:@"loginvideoee"];
bgImgV_2.contentMode = UIViewContentModeScaleAspectFill;
bgImgV_1.contentMode = UIViewContentModeScaleAspectFill;
[self.view addSubview:bgImgV_2];
[self.view addSubview:bgImgV_1];
CFTimeInterval duration = 12;
CABasicAnimation *anim1 = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
anim1.toValue = @(-kScreenHeight);
anim1.duration = duration;
anim1.repeatCount = HUGE_VALF;
anim1.removedOnCompletion = NO; //解决页面切换之后,动画久停止的问题,其实是
[bgImgV_1.layer addAnimation:anim1 forKey:nil];
CABasicAnimation *anim2 = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
anim2.toValue = @(-kScreenHeight);
anim2.duration = duration;
anim2.repeatCount = HUGE_VALF;
anim2.removedOnCompletion = NO;
[bgImgV_2.layer addAnimation:anim2 forKey:nil];
}
@end
解释:为什么动画结束后返回原状态?
首先我们需要搞明白一点的是,layer动画运行的过程是怎样的?其实在我们给一个视图添加layer动画时,真正移动并不是我们的视图本身,而是 presentation layer 的一个缓存。动画开始时 presentation layer开始移动,原始layer隐藏,动画结束时,presentation layer从屏幕上移除,原始layer显示。这就解释了为什么我们的视图在动画结束后又回到了原来的状态,因为它根本就没动过。
这个同样也可以解释为什么在动画移动过程中,我们为何不能对其进行任何操作。
所以在我们完成layer动画之后,最好将我们的layer属性设置为我们最终状态的属性,然后将presentation layer 移除掉。
至此效果上看来是够优雅了,代码不优雅的地方欢迎指正!