在iPhone UIImageView中添加动画Gif图像


Answers:


138
UIImageView* animatedImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
animatedImageView.animationImages = [NSArray arrayWithObjects:    
                               [UIImage imageNamed:@"image1.gif"],
                               [UIImage imageNamed:@"image2.gif"],
                               [UIImage imageNamed:@"image3.gif"],
                               [UIImage imageNamed:@"image4.gif"], nil];
animatedImageView.animationDuration = 1.0f;
animatedImageView.animationRepeatCount = 0;
[animatedImageView startAnimating];
[self.view addSubview: animatedImageView];

您可以加载多个gif图像。

您可以使用以下ImageMagick命令拆分gif :

convert +adjoin loading.gif out%d.gif

1
我需要从UIImageview中的以下URL加载图像。... feedads.g.doubleclick.net/~at/K_fHnmr7a7T0pru2TjQC29TsPYY/1/di
Velmurugan

NSData * mydata = [[NSData分配] initWithContentsOfURL:[NSURL URLWithString:myurl]]; UIImage * myimage = [[UIImage alloc] initWithData:imageData]; 使用它来读取url,然后将此对象添加到数组
Ishu 2010年

8
iPhone操作系统不能也不会正确显示动画GIF图像。UIImage对象不能用于此目的。即使它支持GIF图像,任何动画都将被丢弃,仅显示第一帧。因此,如果您需要在iPhone应用程序中显示GIF动画,就很麻烦。代码需要编写...看看这里:pliep.nl/blog/2009/04/...
fyasar

10
您只需要使用Web视图而不是图像视图
Shreesh Garg

2
github.com/mayoff/uiimage-from-animated-gif只需使用此类别,因为它会自动使答案中描述的所有内容
迈克尔

53

这已经找到了可接受的答案,但是我最近遇到了UIImage + animatedGIF UIImage扩展。它提供以下类别:

+[UIImage animatedImageWithAnimatedGIFURL:(NSURL *)url]

让您简单地:

#import "UIImage+animatedGIF.h"
UIImage* mygif = [UIImage animatedImageWithAnimatedGIFURL:[NSURL URLWithString:@"http://en.wikipedia.org/wiki/File:Rotating_earth_(large).gif"]];

像魔术一样工作。


1
是否有一种方法可以直接在项目中使用文件,而不是从URL加载gif?
juliensaad 2014年

2
UIImage + animatedGIF ...我见过的最好的类别之一...感谢@robmayoff
whyoz 2015年

22

这是使用Gif图像的最佳解决方案。在您的项目中从Github添加SDWebImage。

#import "UIImage+GIF.h"

_imageViewAnimatedGif.image= [UIImage sd_animatedGIFNamed:@"thumbnail"];

这正是我想要的。谢谢你,兄弟!如果我可以添加一件事:UIImageView不能合成,但是应该在情节提要中创建并链接到其IBOutlet :)
Lucia Belardinelli 2015年

12

检查此链接

https://github.com/mayoff/uiimage-from-animated-gif/blob/master/uiimage-from-animated-gif/UIImage%2BanimatedGIF.h

并导入这些clase UIImage + animatedGIF.h,UIImage + animatedGIF.m

使用此代码

 NSURL *urlZif = [[NSBundle mainBundle] URLForResource:@"dots64" withExtension:@"gif"];
 NSString *path=[[NSBundle mainBundle]pathForResource:@"bar180" ofType:@"gif"];
 NSURL *url=[[NSURL alloc] initFileURLWithPath:path];
 imageVw.image= [UIImage animatedImageWithAnimatedGIFURL:url];

希望这对您有所帮助


8

如果您不想使用第3方库,

extension UIImageView {
    func setGIFImage(name: String, repeatCount: Int = 0 ) {
        DispatchQueue.global().async {
            if let gif = UIImage.makeGIFFromCollection(name: name, repeatCount: repeatCount) {
                DispatchQueue.main.async {
                    self.setImage(withGIF: gif)
                    self.startAnimating()
                }
            }
        }
    }

    private func setImage(withGIF gif: GIF) {
        animationImages = gif.images
        animationDuration = gif.durationInSec
        animationRepeatCount = gif.repeatCount
    }
}

extension UIImage {
    class func makeGIFFromCollection(name: String, repeatCount: Int = 0) -> GIF? {
        guard let path = Bundle.main.path(forResource: name, ofType: "gif") else {
            print("Cannot find a path from the file \"\(name)\"")
            return nil
        }

        let url = URL(fileURLWithPath: path)
        let data = try? Data(contentsOf: url)
        guard let d = data else {
            print("Cannot turn image named \"\(name)\" into data")
            return nil
        }

        return makeGIFFromData(data: d, repeatCount: repeatCount)
    }

    class func makeGIFFromData(data: Data, repeatCount: Int = 0) -> GIF? {
        guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
            print("Source for the image does not exist")
            return nil
        }

        let count = CGImageSourceGetCount(source)
        var images = [UIImage]()
        var duration = 0.0

        for i in 0..<count {
            if let cgImage = CGImageSourceCreateImageAtIndex(source, i, nil) {
                let image = UIImage(cgImage: cgImage)
                images.append(image)

                let delaySeconds = UIImage.delayForImageAtIndex(Int(i),
                                                                source: source)
                duration += delaySeconds
            }
        }

        return GIF(images: images, durationInSec: duration, repeatCount: repeatCount)
    }

    class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double {
        var delay = 0.0

        // Get dictionaries
        let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
        let gifPropertiesPointer = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: 0)
        if CFDictionaryGetValueIfPresent(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque(), gifPropertiesPointer) == false {
            return delay
        }

        let gifProperties:CFDictionary = unsafeBitCast(gifPropertiesPointer.pointee, to: CFDictionary.self)

        // Get delay time
        var delayObject: AnyObject = unsafeBitCast(
            CFDictionaryGetValue(gifProperties,
                                 Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()),
            to: AnyObject.self)
        if delayObject.doubleValue == 0 {
            delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties,
                                                             Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self)
        }

        delay = delayObject as? Double ?? 0

        return delay
    }
}

class GIF: NSObject {
    let images: [UIImage]
    let durationInSec: TimeInterval
    let repeatCount: Int

    init(images: [UIImage], durationInSec: TimeInterval, repeatCount: Int = 0) {
        self.images = images
        self.durationInSec = durationInSec
        self.repeatCount = repeatCount
    }
}

要使用

override func viewDidLoad() {
    super.viewDidLoad()
    imageView.setGIFImage(name: "gif_file_name")
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    imageView.stopAnimating()
}

确保将gif文件添加到项目中,而不是.xcassets文件夹中。


您的代码可能引起问题:线程1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)错误!
编码器ACJHP

5

这不满足使用UIImageView的要求,但是也许可以为您简化事情。您是否考虑过使用UIWebView?

NSString *gifUrl = @"http://gifs.com";
NSURL *url = [NSURL URLWithString: gifUrl];
[webView loadRequest: [NSURLRequest requestWithURL:url]

如果需要,可以将HTML文件导入Xcode项目并在字符串中设置根目录,而不是链接到需要Internet的URL。



3

我知道答案已经被批准,但是很难不分享我创建了一个嵌入式框架,该框架向iOS添加了Gif支持,就像您使用任何其他UIKit Framework类一样。

这是一个例子:

UIGifImage *gif = [[UIGifImage alloc] initWithData:imageData];
anUiImageView.image = gif;

https://github.com/ObjSal/UIGifImage/releases下载最新版本

-萨尔


1

如果必须从URL加载gif图片,则始终可以将gif嵌入到的图片标签中UIWebView


1

SWIFT 3

这是需要Swift版本的人的更新!

几天前,我需要做这样的事情。我根据特定的参数从服务器加载了一些数据,与此同时,我想显示“加载”的另一幅gif图像。我一直在寻找一种可以做到这一点的选择,UIImageView但不幸的是,我没有找到无需分割.gif图像就可以做到的事情。因此,我决定使用实现一个解决方案,UIWebView并且我想共享它:

extension UIView{
    func animateWithGIF(name: String){
        let htmlString: String =    "<!DOCTYPE html><html><head><title></title></head>" +
                                        "<body style=\"background-color: transparent;\">" +
                                            "<img src=\""+name+"\" align=\"middle\" style=\"width:100%;height:100%;\">" +
                                        "</body>" +
                                    "</html>"

        let path: NSString = Bundle.main.bundlePath as NSString
        let baseURL: URL = URL(fileURLWithPath: path as String) // to load images just specifying its name without full path

        let frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
        let gifView = UIWebView(frame: frame)

        gifView.isOpaque = false // The drawing system composites the view normally with other content.
        gifView.backgroundColor = UIColor.clear
        gifView.loadHTMLString(htmlString, baseURL: baseURL)

        var s: [UIView] = self.subviews 
        for i in 0 ..< s.count {
            if s[i].isKind(of: UIWebView.self) { s[i].removeFromSuperview() }
        }

        self.addSubview(gifView)
    }

    func animateWithGIF(url: String){
        self.animateWithGIF(name: url)
    }
} 

我做了一个扩展,UIView为其添加了一个UIWebViewas子视图,并显示刚刚通过其名称的.gif图像。

现在在我UIViewControllerUIView名字中有一个“ loadingView”,它是我的“正在加载”指示器,每当我想显示.gif图像时,我都会执行以下操作:

class ViewController: UIViewController {
    @IBOutlet var loadingView: UIView!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        configureLoadingView(name: "loading.gif")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // .... some code
        // show "loading" image
        showLoadingView()
    }

    func showLoadingView(){
        loadingView.isHidden = false
    }
    func hideLoadingView(){
        loadingView.isHidden = true
    }
    func configureLoadingView(name: String){
        loadingView.animateWithGIF(name: "name")// change the image
    }
}

当我想更改gif图片时,只需configureLoadingView()使用新的.gif图片的名称调用该函数并调用showLoadingView()hideLoadingView()一切正常!

但...

...如果您已分割图像,则可以使用如下所示的UIImage静态方法在一行中对其进行动画处理UIImage.animatedImageNamed

imageView.image = UIImage.animatedImageNamed("imageName", duration: 1.0)

从文档:

该方法通过将一系列数字附加到name参数中提供的基本文件名中来加载一系列文件。动画图像中包含的所有图像应共享相同的大小和比例。

或者您可以使用以下UIImage.animatedImageWithImages方法来实现:

let images: [UIImage] = [UIImage(named: "imageName1")!,
                                            UIImage(named: "imageName2")!,
                                            ...,
                                            UIImage(named: "imageNameN")!]
imageView.image = UIImage.animatedImage(with: images, duration: 1.0)

从文档:

从现有图像集中创建并返回动画图像。动画图像中包含的所有图像应共享相同的大小和比例。


0

您可以使用https://github.com/Flipboard/FLAnimatedImage

#import "FLAnimatedImage.h"
NSData *dt=[NSData dataWithContentsOfFile:path];
imageView1 = [[FLAnimatedImageView alloc] init];
FLAnimatedImage *image1 = [FLAnimatedImage animatedImageWithGIFData:dt];
imageView1.animatedImage = image1;
imageView1.frame = CGRectMake(0, 5, 168, 80);
[self.view addSubview:imageView1];

0

斯威夫特3:

如上所述,我将FLAnimatedImage与FLAnimatedImageView一起使用。我正在从xcassets加载gif作为数据集。这使我可以为iPhone和iPad提供不同的gif,以用于外观和应用程序切片。这比我尝试过的任何其他功能都要好得多。使用.stopAnimating()暂停也很容易。

if let asset = NSDataAsset(name: "animation") {
    let gifData = asset.data
    let gif = FLAnimatedImage(animatedGIFData: gifData)
    imageView.animatedImage = gif
  }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.