在Iphone UIImageView中添加动画Gif图像

时间:2010-12-08 10:58:54

标签: objective-c iphone uiimageview

我需要从UIImageview中的URL加载动画Gif图像。

当我使用普通代码时,图像没有加载。

有没有其他方法可以加载动画Gif图像?

12 个答案:

答案 0 :(得分:133)

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 :(得分:50)

这已经找到了接受的答案,但我最近遇到了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"]];

像魔术一样工作。

答案 2 :(得分:22)

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

#import "UIImage+GIF.h"

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

答案 3 :(得分:12)

检查此链接

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

并导入这些clases 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];

希望这是有帮助的

答案 4 :(得分:5)

这不符合使用UIImageView的要求,但这可能会为您简化。你考虑过使用UIWebView吗?

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

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

答案 5 :(得分:4)

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

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文件夹中。

答案 6 :(得分:3)

这是一个有趣的图书馆:https://github.com/Flipboard/FLAnimatedImage

我测试了演示示例,它运行良好。它是UIImageView的孩子。所以我认为你也可以直接在你的故事板中使用它。

干杯

答案 7 :(得分:2)

如果您必须从网址加载gif图片,则始终可以将gif嵌入UIWebView的图片代码中。

答案 8 :(得分: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添加了一个扩展程序,它将UIWebView添加为子视图,并显示.gif图像只是传递其名称。

现在我的UIViewController我有一个UIView名为'loadingView',这是我的'loading'指标,每当我想显示.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图像时,只需使用我的新.gif图像的名称调用函数configureLoadingView()并正确调用showLoadingView()hideLoadingView()一切正常! / p>

但是...

...如果您分割了图像,那么您可以使用名为UIImage的{​​{1}}静态方法在一行中为其设置动画,如下所示:

UIImage.animatedImageNamed

来自文档:

  

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

或者您可以使用imageView.image = UIImage.animatedImageNamed("imageName", duration: 1.0)方法进行此操作:

UIImage.animatedImageWithImages

来自文档:

  

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

答案 9 :(得分: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];

答案 10 :(得分:0)

斯威夫特3:

如上所述我使用FLAnimatedImage和FLAnimatedImageView。我正在将gif作为xcassets的数据集加载。这允许我为iphone和ipad提供不同的GIF,用于外观和应用程序切片。这比我尝试的其他任何东西都要高效得多。使用.stopAnimating()暂停也很容易。

if let asset = NSDataAsset(name: "animation") {
    let gifData = asset.data
    let gif = FLAnimatedImage(animatedGIFData: gifData)
    imageView.animatedImage = gif
  }

答案 11 :(得分:0)

使用 SwiftKingFisher

   lazy var animatedPart: AnimatedImageView = {
        let img = AnimatedImageView()
        if let src = Bundle.main.url(forResource: "xx", withExtension: "gif"){
            img.kf.setImage(with: src)
        }
        return img
   }()