ios 更改 UIImageView 的图像时淡入淡出/溶解

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7638831/
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 21:43:38  来源:igfitidea点击:

Fade/dissolve when changing UIImageView's image

iosobjective-cswiftcocoa-touchuiimageview

提问by Josh Kahane

Rather than creating two UIImageViews, it seems logical to simply change the imageof one view. If I do that, is there anyway of having a fade/cross dissolve between the two images rather than an instant switch?

而不是创建两个UIImageViews,简单地改变image一个视图的似乎是合乎逻辑的。如果我这样做,是否有两个图像之间的淡入淡出/交叉溶解而不是即时切换?

采纳答案by Mirkules

Edit: there is a better solution from @algal below.

编辑:下面的@algal有一个更好的解决方案。

Another way to do this is by using predefined CAAnimation transitions:

另一种方法是使用预定义的 CAAnimation 转换:

CATransition *transition = [CATransition animation];
transition.duration = 0.25;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
transition.delegate = self;
[self.view.layer addAnimation:transition forKey:nil];
view1.hidden = YES;
view2.hidden = NO;

See the View Transitions example project from Apple: https://developer.apple.com/library/content/samplecode/ViewTransitions/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007411

请参阅 Apple 的 View Transitions 示例项目:https: //developer.apple.com/library/content/samplecode/ViewTransitions/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007411

回答by algal

It can be much simpler using the new block-based, UIKit animationmethods.

使用新的基于块的UIKit animation方法可以简单得多。

Suppose the following code is in the view controller, and the UIImageView you want to cross-dissolve is a subview of self.view addressable via the property self.imageViewThen all you need is:

假设下面的代码在视图控制器中,你要交叉溶解的 UIImageView 是 self.view 的一个子视图,可以通过属性寻址,self.imageView那么你需要的就是:

    UIImage * toImage = [UIImage imageNamed:@"myname.png"];
    [UIView transitionWithView:self.imageView
                      duration:5.0f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                      self.imageView.image = toImage;
                    } completion:nil]

Done.

完毕。

And to do it in Swift, it's like so:

要在 Swift 中做到这一点,就像这样:

    let toImage = UIImage(named:"myname.png")
    UIView.transitionWithView(self.imageView,
                              duration:5,
                              options: UIViewAnimationOptions.TransitionCrossDissolve,
                              animations: { self.imageView.image = toImage },
                              completion: nil)

Swift 3, 4 & 5

斯威夫特 3、4 和 5

     let toImage = UIImage(named:"myname.png")
     UIView.transition(with: self.imageView,
                       duration: 0.3,
                       options: .transitionCrossDissolve,
                       animations: {
                           self.imageView.image = toImage
                       },
                       completion: nil)

回答by Sour LeangChhean

For Swift 3.0.1 :

对于 Swift 3.0.1 :

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

Reference: https://gist.github.com/licvido/bc22343cacfa3a8ccf88

参考:https: //gist.github.com/licvido/bc22343cacfa3a8ccf88

回答by Srikar Appalaraju

Yes what you say is absolutely correct and thats the way to do it. I wrote this method & always use this to Fade in my image. I deal with CALayerfor this. You need to import Core Animation for this.

是的,你说的是绝对正确的,这就是这样做的方法。我写了这个方法并总是用它来淡化我的形象。我处理CALayer这个。您需要为此导入核心动画。

+ (void)fadeInLayer:(CALayer *)l
{
    CABasicAnimation *fadeInAnimate   = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeInAnimate.duration            = 0.5;
    fadeInAnimate.repeatCount         = 1;
    fadeInAnimate.autoreverses        = NO;
    fadeInAnimate.fromValue           = [NSNumber numberWithFloat:0.0];
    fadeInAnimate.toValue             = [NSNumber numberWithFloat:1.0];
    fadeInAnimate.removedOnCompletion = YES;
    [l addAnimation:fadeInAnimate forKey:@"animateOpacity"];
    return;
}

You could do the opposite for Fade out an image. After it fades out. You just remove it from superview (which is UIImageView). [imageView removeFromSuperview].

您可以对淡出图像执行相反的操作。淡出之后。您只需从超级视图中删除它(即UIImageView)。[imageView removeFromSuperview].

回答by magma

You could also package the fade-in feature in a subclass, so that you can then use it as a common UIImageView, as in the following example:

您还可以将淡入功能打包在子类中,以便您可以将其用作通用 UIImageView,如下例所示:

IMMFadeImageView *fiv=[[IMMFadeImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
[self.view addSubview:fiv];
fiv.image=[UIImage imageNamed:@"initialImage.png"];
fiv.image=[UIImage imageNamed:@"fadeinImage.png"];  // fades in

A possible implementation follows.

一个可能的实现如下。

Note: the way you actually implement the fade-in in the setImage:function can change, and could be one of the other excellent examples described in the other answers to this question — creating an additional on-the-fly UIImageViewas I'm doing here might be an unacceptable overhead in your specific situation.

注意:您在setImage:函数中实际实现淡入的方式可能会发生变化,并且可能是此问题的其他答案中描述的其他优秀示例之一 -UIImageView像我在这里所做的那样创建一个额外的即时可能在您的特定情况下是不可接受的开销

IMMFadeImageView.h:

IMMFadeImageView.h:

#import <UIKit/UIKit.h>

@interface IMMFadeImageView : UIImageView
@property (nonatomic,assign) float fadeDuration;
@end

IMMFadeImageView.m:

IMMFadeImageView.m:

#import "IMMFadeImageView.h"

@implementation IMMFadeImageView
@synthesize fadeDuration;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.fadeDuration=1;
    }
    return self;
}
-(void)setImage:(UIImage *)newImage{

    if(!self.image||self.fadeDuration<=0){
        super.image=newImage;
    } else {
        UIImageView *iv=[[UIImageView alloc] initWithFrame:self.bounds];
        iv.contentMode=self.contentMode;
        iv.image=super.image;
        iv.alpha=1;
        [self addSubview:iv];
        super.image=newImage;
        [UIView animateWithDuration:self.fadeDuration delay:0 options:UIViewAnimationCurveEaseInOut animations:^{
            iv.alpha=0;
        } completion:^(BOOL finished) {
            [iv removeFromSuperview];
        }];
    }
}

The above code relies on a few assumptions (including ARC being enabled in your XCode project), is only intended as a proof of concept, and in the interest of clarity and focus, it stays relevant by omitting important unrelated code. Please don't just copy-paste it blindly.

上面的代码依赖于一些假设(包括在您的 XCode 项目中启用了 ARC),仅用作概念证明,为了清晰和重点,它通过省略重要的无关代码来保持相关性。请不要盲目复制粘贴。

回答by Christopher

I needed the transition to repeat indefinitely. It took a LOT of trial and error for this one but I finally got the end-result I was looking for. These are code snippets for adding image animation to a UIImageView in a UITableViewCell.

我需要无限期地重复过渡。这件事经过了大量的反复试验,但我终于得到了我想要的最终结果。这些是用于向 UITableViewCell 中的 UIImageView 添加图像动画的代码片段。

Here is the relevant code:

这是相关的代码:

@interface SomeViewController ()
@property(nonatomic, strong) NSMutableArray *imagesArray;
@property(nonatomic, assign) NSInteger varietyImageAnimationIndex;
@property(nonatomic, assign) BOOL varietyImagesAnimated;
@end

@implementation SomeViewController
@synthesize imagesArray;
@synthesize varietyImageAnimationIndex;
@synthesize varietyImagesAnimated;
...

// NOTE: Initialize the array of images in perhaps viewDidLoad method.

-(void)animateImages
{
    varietyImageAnimationIndex++;

    [UIView transitionWithView:varietyImageView
                      duration:2.0f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        varietyImageView.image = [imagesArray objectAtIndex:varietyImageAnimationIndex % [imagesArray count]];
                    } completion:^(BOOL finished) {
                        [self animateImages];
                    }];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   ...
        [cell.imageView setImage:[imagesArray objectAtIndex:0]];


        [self setVarietyImageView:cell.imageView];

        if (! varietyImagesAnimated)
        {
            varietyImagesAnimated = YES;
            [self animateImages];
        }

    ...
    return cell;
}

回答by Pavel

After playing around with UIView.transition()and getting problems with .transitionCrossDissolveoption (I was trying to animate images changing inside one UIImageView and transition occurred instantly without animation) I found out that you just need to add one more option which is letting you animate properties changing inside the view (Swift 4.2):

在玩弄UIView.transition()并遇到.transitionCrossDissolve选项问题后(我试图在一个 UIImageView 内为图像更改设置动画,并且在没有动画的情况下立即发生转换)我发现您只需要再添加一个选项即可让您为视图内更改的属性设置动画(斯威夫特 4.2):

UIView.transition(with: self.imageView,
                   duration: 1,
                   options: [.allowAnimatedContent, .transitionCrossDissolve],
                   animations: { self.imageView.image = newImage },
                   completion: nil)

In addition: if your have any subviews on your imageView, it will be redrawn as well and it could prevent animation. For example, I had subview with blur on my imageView and in that case animation doesn't work. So I just changed my view hierarchy and move blur to its own view and put it over imageView.

另外:如果你的 imageView 有任何子视图,它也会被重绘,它可能会阻止动画。例如,我的 imageView 上有模糊的子视图,在这种情况下动画不起作用。所以我只是改变了我的视图层次结构并将模糊移动到它自己的视图并将它放在 imageView 上。

回答by divyenduz

This is I think the shortest way of doing it. Create a UIView animation and commit it on your imageView.

这是我认为最短的方法。创建一个 UIView 动画并将其提交到您的 imageView 上。

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[myImageView setAlpha:0.0];
[UIView commitAnimations];

回答by Jens Schwarzer

By using the highlightedImageproperty this can be made a bit more simple. Here's an example in Swift 3. First set both normal and highlighted image:

通过使用该highlightedImage属性,这可以变得更简单一些。这是 Swift 3 中的一个示例。首先设置普通图像和高亮图像:

let imageView = UIImageView(image: UIImage(named: "image"), highlightedImage: UIImage(named: "highlightedImage"))

And when you want to change between those animated:

当你想在这些动画之间切换时:

UIView.transition(with: imageView, duration: 0.3, options: .transitionCrossDissolve, animations: { self.imageView.isHighlighted = !self.imageView.isHighlighted}, completion: .none)