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

来源:互联网 发布:国际象棋网络对战 编辑:程序博客网 时间:2024/06/01 18:52

     在移动应用开发中,如果两张图片之间直接进行切换,会显得突兀,用户体验不佳。如果中间能有淡入淡出效果,就会很不错。我们就用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  。欢迎大家访问!

1 0