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

myImageView.image = newImage;

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

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


当前回答

为什么不试试这个呢?

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 3和Swift 4中实现这一点的简单方法:

UIView.transition(with: imageView,
                  duration: 0.75,
                  options: .transitionCrossDissolve,
                  animations: { self.imageView.image = toImage },
                  completion: nil)

这里有一些不同的方法: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])
            }

使用Swift 3

extension UIImageView{   
 var imageWithFade:UIImage?{
        get{
            return self.image
        }
        set{
            UIView.transition(with: self,
                              duration: 0.5, options: .transitionCrossDissolve, animations: {
                                self.image = newValue
            }, completion: nil)
        }
    }
}

用法:

myImageView.imageWithFade = myImage

这太棒了

  self.imgViewPreview.transform = CGAffineTransform(scaleX: 0, y: 0)
          UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
              self.imgViewPreview.image = newImage
              self.imgViewPreview.transform = .identity
          }, completion: nil)