转场动画CATransition

2016-11-19  本文已影响0人  花落星辰

转场动画就是从一个场景以动画的形式过渡到另一个场景

步骤:

1.创建转场动

2.设置转场类型、子类型(可选)及其他属性画

3.设置转场后的新视图并添加动画到图层

常用的转场类型(注意私有API是苹果官方没有公开的动画类型,但是目前通过仍然可以使用):

//添加手势

UISwipeGestureRecognizer *leftSwipeGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(leftSwipe:)];

leftSwipeGesture.direction=UISwipeGestureRecognizerDirectionLeft;

[self.view addGestureRecognizer:leftSwipeGesture];

UISwipeGestureRecognizer *rightSwipeGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(rightSwipe:)];

rightSwipeGesture.direction=UISwipeGestureRecognizerDirectionRight;

[self.view addGestureRecognizer:rightSwipeGesture];

UISwipeGestureRecognizer *topSwipeGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(topSwipe:)];

topSwipeGesture.direction=UISwipeGestureRecognizerDirectionUp;

[self.view addGestureRecognizer:topSwipeGesture];

UISwipeGestureRecognizer *bottomSwipeGesture=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(bottomSwipe:)];

bottomSwipeGesture.direction=UISwipeGestureRecognizerDirectionDown;

[self.view addGestureRecognizer:bottomSwipeGesture];

#pragmamark 向左滑动浏览下一张图片

-(void)leftSwipe:(UISwipeGestureRecognizer *)gesture{

[self transitionAnimation:1];

}

#pragmamark 向右滑动浏览上一张图片

-(void)rightSwipe:(UISwipeGestureRecognizer *)gesture{

[self transitionAnimation:2];

}

-(void)topSwipe:(UISwipeGestureRecognizer *)gesture{

[self transitionAnimation:3];

}

-(void)bottomSwipe:(UISwipeGestureRecognizer *)gesture{

[self transitionAnimation:4];

}

#pragmamark 转场动画

-(void)transitionAnimation:(NSInteger)direction{

//1.创建转场动画对象

CATransition *transition=[[CATransition alloc]init];

//2.设置动画类型,注意对于苹果官方没公开的动画类型只能使用字符串,并没有对应的常量定义

transition.type=@"rippleEffect";

BOOL bl = YES;

//设置子类型

if(direction ==1) {

transition.subtype=kCATransitionFromRight;

bl = YES;

}elseif(direction ==2) {

transition.subtype=kCATransitionFromLeft;

bl = NO;

}elseif(direction ==3) {

transition.subtype=kCATransitionFromTop;

bl = YES;

}else{

transition.subtype=kCATransitionFromBottom;

bl = NO;

}

//设置动画时常

transition.duration=1.0f;

//3.设置转场后的新视图添加转场动画

if(bl) {

currentIndex=(currentIndex+1)%IMAGE_COUNT;

}else{

currentIndex=(currentIndex-1+IMAGE_COUNT)%IMAGE_COUNT;

}

NSString *imageName=[NSString stringWithFormat:@"%d",(int)currentIndex];

_imageView.image = [UIImage imageNamed:imageName];

[_imageView.layer addAnimation:transition forKey:@"KCTransitionAnimation1"];

}

或者用UIView动画来实现转场:

#pragmamark 转场动画

-(void)transitionAnimation:(BOOL)isNext{

UIViewAnimationOptions option;

if(isNext) {

option=UIViewAnimationOptionCurveLinear|UIViewAnimationOptionTransitionFlipFromRight;

}else{

option=UIViewAnimationOptionCurveLinear|UIViewAnimationOptionTransitionFlipFromLeft;

}

[UIView transitionWithView:_imageView duration:1.0options:option animations:^{

_imageView.image=[self getImage:isNext];

} completion:nil];

}

结果:

上一篇下一篇

猜你喜欢

热点阅读