我有一个带有图像的UIImageView。现在我有一个全新的图像(图形文件),并想要在这个UIImageView中显示它。如果我设置
myImageView.image = newImage;
新图像立即可见。不可以做成动画。
我想让它很好地淡出到新图像中。我想也许有比在上面创建一个新的UIImageView并与动画混合更好的解决方案?
我有一个带有图像的UIImageView。现在我有一个全新的图像(图形文件),并想要在这个UIImageView中显示它。如果我设置
myImageView.image = newImage;
新图像立即可见。不可以做成动画。
我想让它很好地淡出到新图像中。我想也许有比在上面创建一个新的UIImageView并与动画混合更好的解决方案?
当前回答
代码:
var fadeAnim:CABasicAnimation = CABasicAnimation(keyPath: "contents");
fadeAnim.fromValue = firstImage;
fadeAnim.toValue = secondImage;
fadeAnim.duration = 0.8; //smoothest value
imageView.layer.addAnimation(fadeAnim, forKey: "contents");
imageView.image = secondImage;
例子:
有趣,更详细的解决方案:(切换水龙头)
let fadeAnim:CABasicAnimation = CABasicAnimation(keyPath: "contents");
switch imageView.image {
case firstImage?:
fadeAnim.fromValue = firstImage;
fadeAnim.toValue = secondImage;
imageView.image = secondImage;
default:
fadeAnim.fromValue = secondImage;
fadeAnim.toValue = firstImage;
imageView.image = firstImage;
}
fadeAnim.duration = 0.8;
imageView.layer.addAnimation(fadeAnim, forKey: "contents");
其他回答
这里有一些不同的方法:UIAnimations,在我看来,这听起来像是你的挑战。
编辑:我太懒了:)
在这篇文章中,我提到了这个方法:
[newView setFrame:CGRectMake( 0.0f, 480.0f, 320.0f, 480.0f)]; //notice this is OFF screen!
[UIView beginAnimations:@"animateTableView" context:nil];
[UIView setAnimationDuration:0.4];
[newView setFrame:CGRectMake( 0.0f, 0.0f, 320.0f, 480.0f)]; //notice this is ON screen!
[UIView commitAnimations];
但是不是动画帧,而是动画alpha:
[newView setAlpha:0.0]; // set it to zero so it is all gone.
[UIView beginAnimations:@"animateTableView" context:nil];
[UIView setAnimationDuration:0.4];
[newView setAlpha:0.5]; //this will change the newView alpha from its previous zero value to 0.5f
[UIView commitAnimations];
斯威夫特5:
当处理collectionView时。只加载一个项目或多个项目的动画。当改变单元格图像时,我尝试了一些不同的动画选项,没有区别,所以我没有在这里指明动画名称。
UIView.animate(withDuration: 1.0) { [weak self] in
guard let self = self else { return print("gotchya!") }
self.collectionView.reloadItems(at: [indexPath])
}
在iOS 5中,这就简单多了:
[newView setAlpha:0.0];
[UIView animateWithDuration:0.4 animations:^{
[newView setAlpha:0.5];
}];
为什么不试试这个呢?
NSArray *animationFrames = [NSArray arrayWithObjects:
[UIImage imageWithName:@"image1.png"],
[UIImage imageWithName:@"image2.png"],
nil];
UIImageView *animatedImageView = [[UIImageView alloc] init];
animatedImageView.animationImages = animationsFrame;
[animatedImageView setAnimationRepeatCount:1];
[animatedImageView startAnimating];
快速版本:
let animationsFrames = [UIImage(named: "image1.png"), UIImage(named: "image2.png")]
let animatedImageView = UIImageView()
animatedImageView.animationImages = animationsFrames
animatedImageView.animationRepeatCount = 1
animatedImageView.startAnimating()
Swift 5扩展:
extension UIImageView{
func setImage(_ image: UIImage?, animated: Bool = true) {
let duration = animated ? 0.3 : 0.0
UIView.transition(with: self, duration: duration, options: .transitionCrossDissolve, animations: {
self.image = image
}, completion: nil)
}
}