当改变UIImageView的image属性时,UI会立刻从一张图片切换到另一张图片,显得十分生硬,本文记录如何为改变UIImageView的image属性时加入淡入淡出的效果。
现在有四张UIImage,初始化后将其存入数组中:
1 2 3 4 5
| self.imgs = @[[UIImage imageNamed:@"bg01"], [UIImage imageNamed:@"bg02"], [UIImage imageNamed:@"bg03"], [UIImage imageNamed:@"bg04"]]; self.imageView.image = self.imgs[0];
|
有一按钮,其事件如下:
1 2 3
| - (IBAction)switchImg:(id)sender { }
|
现在填充其实现来完成UIImageView改变image时加入1秒的淡入淡出
方法1. 使用CATransition
1 2 3 4 5 6 7 8 9 10
| 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
1 2 3 4 5 6 7
| 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
目前已转行教育行业,欢迎加微信交流:CaryaLiu