Skip to content

Instantly share code, notes, and snippets.

@piemonte
Created October 12, 2022 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piemonte/80f3efca768d2fa91c32ddc97be5a844 to your computer and use it in GitHub Desktop.
Save piemonte/80f3efca768d2fa91c32ddc97be5a844 to your computer and use it in GitHub Desktop.
//
// UIImage+GIF.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015-present patrick piemonte (http://patrickpiemonte.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import Foundation
extension UIImage {
public class func gifImage(withData data: Data) -> UIImage? {
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
return nil
}
return UIImage.animatedImage(withSource: source)
}
public class func gifImage(withUrl gifUrl: String) -> UIImage? {
guard let bundleURL: URL = URL(string: gifUrl) else {
return nil
}
guard let imageData = try? Data(contentsOf: bundleURL) else {
return nil
}
return gifImage(withData: imageData)
}
public class func gifImage(withFilename filename: String) -> UIImage? {
guard let bundleURL = Bundle.main.url(forResource: filename, withExtension: "gif") else {
return nil
}
guard let imageData = try? Data(contentsOf: bundleURL) else {
return nil
}
return gifImage(withData: imageData)
}
// MARK: - private
private class func delayForImageAtIndex(_ index: Int, source: CGImageSource!) -> Double {
var delay = 0.05
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.doubleValue
if delay < 0.05 {
delay = 0.05
}
return delay
}
private class func gcd(forDelays delays: [Int]) -> Int {
if delays.isEmpty {
return 1
}
var gcd = delays[0]
for val in delays {
gcd = UIImage.gcd(val, gcd)
}
return gcd
}
private class func animatedImage(withSource 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(Int(i), source: source)
// sec to ms
delays.append(Int(delaySeconds * 1000.0))
}
let duration: Int = {
var sum = 0
for val: Int in delays {
sum += val
}
return sum
}()
let gcd = gcd(forDelays: 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)
}
}
return UIImage.animatedImage(with: frames, duration: Double(duration) / 1000.0)
}
}
// MARK: - gcd, greatest common divisor
extension UIImage {
/// https://victorqi.gitbooks.io/swift-algorithm/content/greatest_common_divisor.html
public class func gcd(_ m: Int, _ n: Int) -> Int {
var a = 0
var b = max(m, n)
var r = min(m, n)
while r != 0 {
a = b
b = r
r = a % b
}
return b
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment