在Iphone UIImageView中添加动画Gif图像

Vel*_*gan 73 iphone objective-c uiimageview

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

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

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

Ish*_*shu 134

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];
Run Code Online (Sandbox Code Playgroud)

您可以加载多个gif图像.

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

convert +adjoin loading.gif out%d.gif
Run Code Online (Sandbox Code Playgroud)

  • 您只需使用Web视图而不是图像视图 (10认同)
  • iPhone OS无法也不会正确显示动画GIF图像.UIImage对象不能用于此目的.即使它支持GIF图像,任何动画都将被丢弃,只显示第一帧.所以,如果你需要在iPhone应用程序中显示一个动画GIF,你就搞砸了.代码需要编写...请看这里:http://www.pliep.nl/blog/2009/04/iphone_developer_decoding_an_animated_gif_image_in_objc (8认同)
  • 嗨,谢谢你的回复...但我需要,我将从网址加载GIF图像... (6认同)
  • https://github.com/mayoff/uiimage-from-animated-gif只需使用此类别,因为它会自动在答案中描述所有内容 (2认同)

Dom*_*ard 52

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

+[UIImage animatedImageWithAnimatedGIFURL:(NSURL *)url]
Run Code Online (Sandbox Code Playgroud)

允许您简单地:

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

像魔术一样工作.

  • UIImage + animatedGIF ...我见过的最好的类别之一...谢谢@robmayoff (2认同)

Arv*_*mar 22

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

#import "UIImage+GIF.h"

_imageViewAnimatedGif.image= [UIImage sd_animatedGIFNamed:@"thumbnail"];
Run Code Online (Sandbox Code Playgroud)


小智 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];
Run Code Online (Sandbox Code Playgroud)

希望这是有帮助的


Suk*_*won 7

如果您不想使用3rd party库,

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
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用,

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

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    imageView.stopAnimating()
}
Run Code Online (Sandbox Code Playgroud)

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


tre*_*son 5

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

NSString *gifUrl = @"http://gifs.com";
NSURL *url = [NSURL URLWithString: gifUrl];
[webView loadRequest: [NSURLRequest requestWithURL:url]
Run Code Online (Sandbox Code Playgroud)

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