CATransition 过渡动画
属性动画只能对图层的可动画属性起作用,如果要改变一个不能动画的属性(比如图片,背景颜色),或者从层级关系中添加或者移除图层,属性动画将不起作用.这里就要使用过渡动画CATransition.
CATransition 是CAAnimation的子类,它有type和subType来标识变换效果.
type类型如下:
名称 | 描述 |
---|---|
kCATransitionFade | 默认效果,淡入淡出 |
kCATransitionMoveIn | 新图层从边缘的一侧滑入,将旧图层从另一侧推出 |
kCATransitionPush | 新图层从边缘的一侧滑入,但是不推出旧图层 |
kCATransitionReveal | 新图层在旧图层下方,旧图层滑出 |
可以看到,后三种类型有方向.这个由subType控制.可以设置上下左右四个方向,默认从左侧滑入.
下面的代码能实现使用动画效果切换image
- (void)changeImage
{
[_imageView.layer removeAllAnimations];
CATransition *transition = [CATransition animation];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;
[_imageView.layer addAnimation:transition forKey:nil];
_imageIndex = (_imageIndex >= self.animateArray.count -1) ? 0 : (_imageIndex + 1);
_imageView.image = [self.animateArray objectAtIndex:_imageIndex];
}
- (void)startTimer
{
[self invilateTimer];
__weak typeof(self) weakSelf = self;
_timer = [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:YES block:^(NSTimer * _Nonnull timer) {
__strong typeof(weakSelf) strongSelf = weakSelf;
[strongSelf changeImage];
}];
}
- (void)invilateTimer
{
if (_timer)
{
[_timer invalidate];
_timer = nil;
}
}
这里要注意,虽然过渡动画和之前的属性动画或者动画组添加到图层上的方式一致,都是通过addAnimation:forKey:方法.但是和属性动画不同的是,对指定的图层一次只能使用一次CATransition,所以过渡动画的key总是”transition”.