- 首页 > it技术 > >
进阶|进阶 12-5 转场动画
#import "ViewController.h"
#define IMAGE_COUNT 5
@interface ViewController ()
/*图片 */
@property (strong,nonatomic) UIImageView *imageView;
/* 当前下标*/
@property (assign,nonatomic) NSInteger currentIndex;
@end@implementation ViewController- (void)viewDidLoad {
[super viewDidLoad];
self.imageView = [[UIImageView alloc] init];
self.imageView.frame = [UIScreen mainScreen].bounds;
//这个图片会在View中显示,并且比例不变
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
self.imageView.image = [UIImage imageNamed:@"0.jpg"];
[self.view addSubview:self.imageView];
//添加手势
UISwipeGestureRecognizer *left = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipe:)];
left.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:left];
UISwipeGestureRecognizer *right = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipe:)];
right.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:right];
}- (void)leftSwipe:(UISwipeGestureRecognizer *)gestur{
[self transitionAnimation:YES];
}
- (void)rightSwipe:(UISwipeGestureRecognizer *)gestur{
[self transitionAnimation:NO];
}- (void)transitionAnimation:(BOOL)isNext{
//1.创建转场动画
CATransition *tran = [[CATransition alloc] init];
//效果
tran.type = @"cube";
if (isNext) {
tran.subtype = kCATransitionFromRight;
}else{
tran.subtype = kCATransitionFromLeft;
}tran.duration = 1.0f;
self.imageView.image = [self getImage:isNext];
[self.imageView.layer addAnimation:tran forKey:@"Transition"];
}- (UIImage *)getImage:(BOOL)isNext{
//后一张
if (isNext) {self.currentIndex = (self.currentIndex + 1) % IMAGE_COUNT;
}else{
self.currentIndex = (self.currentIndex - 1 + IMAGE_COUNT) % IMAGE_COUNT;
}//往数组中添加图片,图片名与下标名对应
NSString *imageName = [NSString stringWithFormat:@"%ld.jpg",self.currentIndex];
return [UIImage imageNamed:imageName];
}@end
推荐阅读