您的位置:首页 > 移动开发 > IOS开发

iOS项目开发实战——使用CALayer实现图片的淡入淡出效果

2015-09-20 20:48 1101 查看
     在移动应用开发中,如果两张图片之间直接进行切换,会显得突兀,用户体验不佳。如果中间能有淡入淡出效果,就会很不错。我们就用CALayer来实现一下:

(1)拖入2张图片,然后代码实现如下:

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic,strong) CALayer *imageLayer;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

UIImage *image1 = [UIImage imageNamed:@"img1"];

//创建出图片layer;
self.imageLayer = [CALayer  layer];
self.imageLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
[self.view.layer addSublayer:self.imageLayer];

self.imageLayer.contents = (__bridge id)(image1.CGImage);

[self performSelector:@selector(layerAnimation) withObject:nil afterDelay:3.0f];

}

- (void) layerAnimation{

UIImage *image2 = [UIImage imageNamed:@"img2"];

//图片动画;
CABasicAnimation *contentsAnimation = [CABasicAnimation animationWithKeyPath:@"contents"];
contentsAnimation.fromValue = self.imageLayer.contents;
contentsAnimation.toValue = (__bridge id)(image2.CGImage);
contentsAnimation.duration = 2;

//设定layer动画结束之后的值,(必须设定,否则会恢复到动画之前的状态)
self.imageLayer.contents = (__bridge id)(image2.CGImage);

//提交动画;
[self.imageLayer addAnimation:contentsAnimation forKey:nil];

}

@end


(2)实现效果如下:










(3)这样的图片切换很舒服,淡入淡出时间可以自己设置。

github主页:https://github.com/chenyufeng1991  。欢迎大家访问!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: