iOS:核心动画之转场动画CATransition
转场动画——CATransition
CATransition是CAAnimation的子类,用于做转场动画,能够为层提供移出屏幕和移入屏幕的动画效果。iOS比Mac OS X的转场动画效果少一点
UINavigationController就是通过CATransition实现了将控制器的视图推入屏幕的动画效果
动画属性:
–type:动画过渡类型
–subtype:动画过渡方向
–startProgress:动画起点(在整体动画的百分比)
–endProgress:动画终点(在整体动画的百分比)
过渡效果:
过渡方向:
CA_EXTERN NSString * const kCATransitionFromRight //动画从右往左
CA_EXTERN NSString * const kCATransitionFromLeft //动画从左往右
CA_EXTERN NSString * const kCATransitionFromTop //动画从下往上
CA_EXTERN NSString * const kCATransitionFromBottom //动画从上往下
具体实例如下:
实现功能:往工程中导入5张图片素材,创建图像视图控件,然后通过向左或向右扫动手势实现图像视图中图片的轮换,即实现转场动画。
代码如下:
//导入图片素材
//声明属性
#import "ViewController.h" @interface ViewController () @property (strong,nonatomic)UIImageView *imageView;//图像视图 @property (assign,nonatomic)NSInteger index; //当前图片的索引 @end
//初始化,创建图像视图控件并设置图片,同时创建扫动手势,添加扫动事件
- (void)viewDidLoad { [super viewDidLoad]; //设置当前图片为第一张 self.index = 1; //初始化图像视图 self.imageView = [[UIImageView alloc]initWithFrame:self.view.frame]; self.imageView.contentMode = UIViewContentModeScaleAspectFit; [self.imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"s%ld.jpg",self.index]]]; //允许图像视图进行用户交互 self.imageView.userInteractionEnabled = YES; [self.view addSubview:self.imageView]; //创建扫动手势 UISwipeGestureRecognizer *leftswipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipe:)]; //设置扫动方向为向左扫 leftswipe.direction = UISwipeGestureRecognizerDirectionLeft; //添加扫动手势 [self.imageView addGestureRecognizer:leftswipe]; //创建扫动手势 UISwipeGestureRecognizer *rightswipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipe:)]; //设置扫动方向为向右扫 rightswipe.direction = UISwipeGestureRecognizerDirectionRight; //添加扫动手势 [self.imageView addGestureRecognizer:rightswipe]; }
//处理扫动手势事件,进行转场动画的创建并执行动画
#pragma mark -扫动手势 -(void)swipe:(UISwipeGestureRecognizer *)sender { //根据手势的方向改变图片的索引,一共5张图片 if (sender.direction == UISwipeGestureRecognizerDirectionLeft)//向左扫 { if (self.index >1 ) { self.index--; } else { self.index = 5; } } else //向右扫 { if (self.index <5) { self.index++; } else { self.index = 1; } } //添加转场动画 CATransition *transition = [[CATransition alloc]init]; //过渡类型类立方体翻转效果 transition.type = @"cube"; //过渡方向为从下往上翻转 transition.subtype = kCATransitionFromBottom; //动画持续时间 transition.duration = 1.0f; //添加转场动画 [self.imageView.layer addAnimation:transition forKey:@"transition"]; //设置每一次转场动画后的图像视图的图片 [self.imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"s%ld.jpg",self.index]]]; }
演示结果如下:
开始时: 左扫或者右扫时:动画立体式的从上往下翻转
程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!