如何在Swift中加载GIF图像?

Mar*_*ius 50 uiimageview uiviewanimation ios swift

我有一个带有GIF横幅的字符串,我需要将其放入应用程序.

我的代码:

func showAdd(){
    Request.get("http://www.kyst.no/api/?apiMode=advertisement&lang=no", { (error: NSError?, data: NSData, text: NSString?) -> () in
        let jsonResult: Dictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
        var banner : NSString = jsonResult["advertisement"]!["banner"] as NSString
        self.addViewImage.image = UIImage.animatedImageNamed(banner, duration: 1)
    })
}
Run Code Online (Sandbox Code Playgroud)

但没有任何反应.请帮忙.

Kir*_*odi 105

加载GIF图像Swift:

#1:从此链接复制swift文件 :

#2:使用名称加载GIF图像

    let jeremyGif = UIImage.gifImageWithName("funny")
    let imageView = UIImageView(image: jeremyGif)
    imageView.frame = CGRect(x: 20.0, y: 50.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView)
Run Code Online (Sandbox Code Playgroud)

#3:使用数据加载GIF图像

    let imageData = try? Data(contentsOf: Bundle.main.url(forResource: "play", withExtension: "gif")!)
    let advTimeGif = UIImage.gifImageWithData(imageData!)
    let imageView2 = UIImageView(image: advTimeGif)
    imageView2.frame = CGRect(x: 20.0, y: 220.0, width: 
    self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView2)
Run Code Online (Sandbox Code Playgroud)

#4:使用URL加载GIF图像

    let gifURL : String = "http://www.gifbin.com/bin/4802swswsw04.gif"
    let imageURL = UIImage.gifImageWithURL(gifURL)
    let imageView3 = UIImageView(image: imageURL)
    imageView3.frame = CGRect(x: 20.0, y: 390.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView3)
Run Code Online (Sandbox Code Playgroud)

下载演示代码

输出:

iPhone 8/iOS 11/xCode 9

在此输入图像描述

  • 这个lib使用了太多的内存, (6认同)
  • @KiritModi这个库使用了太多的内存,并导致很多内存泄漏 (4认同)
  • 如何调整动画速度? (3认同)
  • 对于此功能的未来用户,这不适用于 JPG 或 PNG。如果您正在加载 URL 列表或者您不知道扩展名,它将失败。 (2认同)
  • successGIF.image = UIImage.gifImageWithName("translation-successful") 像这样使用,只是想显示 GIF 的名称。这里我们怎么能只显示一次 (2认同)

smo*_*mut 10

如果有人告诉我将 gif 放入任何文件夹而不是 asset 文件夹中,那就太好了

  • 确切地!迷失了30多分钟 (3认同)

小智 8

//
//  iOSDevCenters+GIF.swift
//  GIF-Swift
//
//  Created by iOSDevCenters on 11/12/15.
//  Copyright © 2016 iOSDevCenters. All rights reserved.
//
import UIKit
import ImageIO


extension UIImage {

public class func gifImageWithData(data: NSData) -> UIImage? {
    guard let source = CGImageSourceCreateWithData(data, nil) else {
        print("image doesn't exist")
        return nil
    }

    return UIImage.animatedImageWithSource(source: source)
}

public class func gifImageWithURL(gifUrl:String) -> UIImage? {
    guard let bundleURL = NSURL(string: gifUrl)
        else {
            print("image named \"\(gifUrl)\" doesn't exist")
            return nil
    }
    guard let imageData = NSData(contentsOf: bundleURL as URL) else {
        print("image named \"\(gifUrl)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

public class func gifImageWithName(name: String) -> UIImage? {
    guard let bundleURL = Bundle.main
        .url(forResource: name, withExtension: "gif") else {
            print("SwiftGif: This image named \"\(name)\" does not exist")
            return nil
    }

    guard let imageData = NSData(contentsOf: bundleURL) else {
        print("SwiftGif: Cannot turn image named \"\(name)\" into NSData")
        return nil
    }

    return gifImageWithData(data: imageData)
}

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

    let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
    let gifProperties: CFDictionary = unsafeBitCast(CFDictionaryGetValue(cfProperties, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()), to: CFDictionary.self)

    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

    if delay < 0.1 {
        delay = 0.1
    }

    return delay
}

class func gcdForPair(a: Int?, _ b: Int?) -> Int {
    var a = a
    var b = b
    if b == nil || a == nil {
        if b != nil {
            return b!
        } else if a != nil {
            return a!
        } else {
            return 0
        }
    }

    if a! < b! {
        let c = a!
        a = b!
        b = c
    }

    var rest: Int
    while true {
        rest = a! % b!

        if rest == 0 {
            return b!
        } else {
            a = b!
            b = rest
        }
    }
}

class func gcdForArray(array: Array<Int>) -> Int {
    if array.isEmpty {
        return 1
    }

    var gcd = array[0]

    for val in array {
        gcd = UIImage.gcdForPair(a: val, gcd)
    }

    return gcd
}

class func animatedImageWithSource(source: CGImageSource) -> UIImage? {
    let count = CGImageSourceGetCount(source)
    var images = [CGImage]()
    var delays = [Int]()

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

        let delaySeconds = UIImage.delayForImageAtIndex(index: Int(i), source: source)
        delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
    }

    let duration: Int = {
        var sum = 0

        for val: Int in delays {
            sum += val
        }

        return sum
    }()

    let gcd = gcdForArray(array: delays)
    var frames = [UIImage]()

    var frame: UIImage
    var frameCount: Int
    for i in 0..<count {
        frame = UIImage(cgImage: images[Int(i)])
        frameCount = Int(delays[Int(i)] / gcd)

        for _ in 0..<frameCount {
            frames.append(frame)
        }
    }

    let animation = UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0)

    return animation
}
}
Run Code Online (Sandbox Code Playgroud)

这是为Swift 3更新的文件

  • 这个内存使用率异常高,单个较大,6mb gif内存使用率为400MB.实际设备不是模拟器.虽然没有尝试过很多其他的GIF. (4认同)
  • @SamBing 我确实尝试在一个单独的项目中使用 Gifu 并使其正常工作。谢谢。我正在从事的项目正在使用“SDWebImage”库,因此我更新了 pod 以支持 gif 并显示了 gif,内存消耗也很好。你也可以看一下:) (2认同)

小智 8

首先安装一个吊舱:-

pod 'SwiftGifOrigin'
Run Code Online (Sandbox Code Playgroud)

并导入您的班级

import SwiftGifOrigin
Run Code Online (Sandbox Code Playgroud)

然后在viewDidiload方法中编写此代码

yourImageView.image = UIImage.gif(name: "imageName")
Run Code Online (Sandbox Code Playgroud)

注意:-plz在gif文件名中不包括文件扩展名。例如:-

//Don't Do this
yourImageView.image = UIImage.gif(name: "imageName.gif")
Run Code Online (Sandbox Code Playgroud)

参见源代码:https : //github.com/swiftgif/SwiftGif

  • 没有关于该库如何工作的解释-如果该库突然开始出现故障,损坏或必须以其他方式删除它,应该如何继续显示GIF图像?请尝试解释库的功能。 (2认同)
  • 向项目中添加 pod 从来都不是解决方案! (2认同)

小智 8

你可以试试这个新库。JellyGif 尊重 Gif 帧持续时间,同时具有高 CPU 和内存性能。它也适用于 UITableViewCell 和 UICollectionViewCell。要开始,您只需要

import JellyGif

let imageView = JellyGifImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

//Animates Gif from the main bundle
imageView.startGif(with: .name("Gif name"))

//Animates Gif with a local path
let url = URL(string: "Gif path")!
imageView.startGif(with: .localPath(url))

//Animates Gif with data
imageView.startGif(with: .data(Data))
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以查看其自述文件


Moc*_*cha 5

本地gif的简单扩展。从gif获取所有图像,并将其添加到imageView animationImages。

extension UIImageView {
    static func fromGif(frame: CGRect, resourceName: String) -> UIImageView? {
        guard let path = Bundle.main.path(forResource: resourceName, ofType: "gif") else {
            print("Gif does not exist at that path")
            return nil
        }
        let url = URL(fileURLWithPath: path)
        guard let gifData = try? Data(contentsOf: url),
            let source =  CGImageSourceCreateWithData(gifData as CFData, nil) else { return nil }
        var images = [UIImage]()
        let imageCount = CGImageSourceGetCount(source)
        for i in 0 ..< imageCount {
            if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
                images.append(UIImage(cgImage: image))
            }
        }
        let gifImageView = UIImageView(frame: frame)
        gifImageView.animationImages = images
        return gifImageView
    }
}
Run Code Online (Sandbox Code Playgroud)

使用方法:

 guard let confettiImageView = UIImageView.fromGif(frame: view.frame, resourceName: "confetti") else { return }
 view.addSubview(confettiImageView)
 confettiImageView.startAnimating()
Run Code Online (Sandbox Code Playgroud)

使用UIImageView API进行重复和持续时间自定义。

confettiImageView.animationDuration = 3
confettiImageView.animationRepeatCount = 1
Run Code Online (Sandbox Code Playgroud)

  • 我使用这种方法在 collectionView 中加载一些 gif,我的应用程序使用了超过 2GB 的内存。使用这样的 gif 似乎非常消耗内存。 (2认同)
  • 完成动画后,执行“confettiImageView.animationImages = nil”,这将释放内存。 (2认同)