ios 如何为 UIImageView 中的图像变化设置动画?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2834573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:14:58  来源:igfitidea点击:

How to animate the change of image in an UIImageView?

iosiphoneanimationuiimageviewuiimage

提问by dontWatchMyProfile

I have an UIImageViewwith an image. Now I have a completely new image (graphic file), and want to display that in this UIImageView. If I just set

我有UIImageView一个图像。现在我有一个全新的图像(图形文件),并想在这个UIImageView. 如果我只是设置

myImageView.image = newImage;

the new image is visible immediately. Not animatable.

新图像立即可见。不可动画。

I want it to nicely fade into the new image. I thought maybe there's a better solution than just creating a new UIImageViewon top of that and blending with animation?

我希望它很好地淡入新图像中。我想也许有更好的解决方案,而不仅仅是UIImageView在此基础上创建一个新的并与动画混合?

回答by Ilker Baltaci

[UIView transitionWithView:textFieldimageView
                  duration:0.2f
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                    imageView.image = newImage;
                } completion:nil];

is another possibility

是另一种可能

回答by Vladimir

I am not sure if you can animate UIViews with fade effect as it seems all supported view transitions are defined in UIViewAnimationTransitionenumeration. Fading effect can be achieved using CoreAnimation. Sample example for this approach:

我不确定您是否可以使用淡入淡出效果为 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];

回答by Zia

In the words of Michael Scott, keep it simple stupid. Here is a simple way to do this in Swift 3and Swift 4:

用迈克尔斯科特的话来说,保持简单愚蠢。这是在Swift 3Swift 4 中执行此操作的简单方法:

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

回答by Zorayr

Here is one example in Swiftthat will first cross dissolve a new image and then add a bouncy animation:

这是Swift中的一个示例,它首先交叉溶解一张新图像,然后添加一个有弹性的动画:

var selected: Bool {
  willSet(selected) {
    let expandTransform:CGAffineTransform = CGAffineTransformMakeScale(1.15, 1.15);
    if (!self.selected && selected) {
      UIView.transitionWithView(self.imageView,
        duration:0.1,
        options: UIViewAnimationOptions.TransitionCrossDissolve,
        animations: {
          self.imageView.image = SNStockCellSelectionAccessoryViewImage(selected)
          self.imageView.transform = expandTransform
        },
        completion: {(finished: Bool) in
          UIView.animateWithDuration(0.4,
            delay:0.0,
            usingSpringWithDamping:0.40,
            initialSpringVelocity:0.2,
            options:UIViewAnimationOptions.CurveEaseOut,
            animations: {
              self.imageView.transform = CGAffineTransformInvert(expandTransform)
            }, completion:nil)
      })
    }
  }
}

var imageView:UIImageView

If imageViewis correctly added to the view as a subview, toggling between selected = falseto selected = trueshould swap the image with a bouncy animation. SNStockCellSelectionAccessoryViewImagejust returns a different image based on the current selection state, see below:

如果imageView作为子视图正确添加到视图中,则在selected = falseto之间切换selected = true应该用有弹性的动画交换图像。SNStockCellSelectionAccessoryViewImage只是根据当前选择状态返回不同的图像,见下文:

private let SNStockCellSelectionAccessoryViewPlusIconSelected:UIImage = UIImage(named:"PlusIconSelected")!
private let SNStockCellSelectionAccessoryViewPlusIcon:UIImage = UIImage(named:"PlusIcon")!

private func SNStockCellSelectionAccessoryViewImage(selected:Bool) -> UIImage {
  return selected ? SNStockCellSelectionAccessoryViewPlusIconSelected : SNStockCellSelectionAccessoryViewPlusIcon
}

The GIF example below is a bit slowed down, the actual animation happens faster:

下面的 GIF 示例有点慢,实际动画发生得更快:

                                       UIImageView bounce animation Gif

                                       UIImageView 弹跳动画 Gif

回答by J-Dizzle

Code:

代码:

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;

Example:

例子:

UIImageView Example from code

代码中的 UIImageView 示例

Fun, More Verbose Solution: (Toggling on a tap)

有趣,更详细的解决方案:(点击切换

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

回答by Peter Stajger

Try this:

尝试这个:

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

回答by M.Nadeeshan

With Swift 3

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

Usage:

用法:

myImageView.imageWithFade = myImage

回答by William Hu

Why not try this.

为什么不试试这个。

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];

A swift version:

一个快速版本:

let animationsFrames = [UIImage(named: "image1.png"), UIImage(named: "image2.png")]
let animatedImageView = UIImageView()
animatedImageView.animationImages = animationsFrames
animatedImageView.animationRepeatCount = 1
animatedImageView.startAnimating()

回答by kas-kad

CABasicAnimation* fadeAnim = [CABasicAnimation animationWithKeyPath:@"contents"];
fadeAnim.fromValue = (__bridge id)imageView.image.CGImage;
fadeAnim.toValue = (__bridge id)[UIImage imageNamed:@"newImage.png"].CGImage;
fadeAnim.duration = 2.0;
[imageView.layer addAnimation:fadeAnim forKey:@"contents"];
imageView.layer.contents = (__bridge id)[UIImage imageNamed:@"newImage.png"].CGImage;

回答by RickiG

There are a few different approaches here: UIAnimations to my recollection it sounds like your challenge.

这里有几种不同的方法:UIAnimations在我的记忆中,这听起来像是你的挑战。

Edit: too lazy of me:)

编辑:我太懒了:)

In the post, I was referring to this method:

在帖子中,我指的是这种方法:

[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];

But instead of animation the frame, you animate the alpha:

但不是动画帧,而是动画 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];