我有一个带有图像的UIImageView。现在我有一个全新的图像(图形文件),并想要在这个UIImageView中显示它。如果我设置

myImageView.image = newImage;

新图像立即可见。不可以做成动画。

我想让它很好地淡出到新图像中。我想也许有比在上面创建一个新的UIImageView并与动画混合更好的解决方案?


当前回答

斯威夫特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];
}];

试试这个:

_imageView.image = image;
[_imageView.layer addAnimation:[CATransition animation] forKey:kCATransition];

我不确定你是否可以用渐隐效果动画UIViews,因为似乎所有支持的视图转换都在UIViewAnimationTransition枚举中定义。渐变效果可以使用CoreAnimation实现。该方法的示例示例:

#import <QuartzCore/QuartzCore.h>
...
imageView.image = [UIImage imageNamed:(i % 2) ? @"3.jpg" : @"4.jpg"];

CATransition *transition = [CATransition animation];
transition.duration = 1.0f;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;

[imageView.layer addAnimation:transition forKey:nil];

代码:

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");

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)
    }
}