iOS改变UIImageView的image时添加渐变

欢迎到个人博客: liumh.com查看本文。

本文为原创,未经允许勿转载

当改变UIImageView的image属性时,UI会立刻从一张图片切换到另一张图片,显得十分生硬,本文记录如何为改变UIImageView的image属性时加入淡入淡出的效果。

现在有四张UIImage,初始化后将其存入数组中:

self.imgs = @[[UIImage imageNamed:@"bg01"],
              [UIImage imageNamed:@"bg02"],
              [UIImage imageNamed:@"bg03"],
              [UIImage imageNamed:@"bg04"]];
self.imageView.image = self.imgs[0];

有一按钮,其事件如下:

- (IBAction)switchImg:(id)sender { }

现在填充其实现来完成UIImageView改变image时加入1秒的淡入淡出

方法1. 使用CATransition

CATransition *transition = [CATransition animation];
transition.type = kCATransitionFade;
transition.duration = 1.0f;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self.imageView.layer addAnimation:transition forKey:nil];

UIImage *currentImage = self.imageView.image;
NSUInteger index = [self.imgs indexOfObject:currentImage];
index = (index + 1) % [self.imgs count];
self.imageView.image = self.imgs[index];

方法2. 使用UIView类方法transitionWithView

UIImage *currentImage = self.imageView.image;
NSUInteger index = [self.imgs indexOfObject:currentImage];
index = (index + 1) % [self.imgs count];

[UIView transitionWithView:self.imageView duration:1 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
    self.imageView.image = self.imgs[index];
} completion:nil];

参考: stackoverflow

如果觉得本文对你有帮助,就请用微信打赏我吧^_^

iOS改变UIImageView的image时添加渐变_第1张图片

你可能感兴趣的:(ios,UIImageView)