Skip to content

Instantly share code, notes, and snippets.

@JasonCanCode
Created July 10, 2019 15:23
Show Gist options
  • Save JasonCanCode/bcd42d169d9dc20130721b049921cbae to your computer and use it in GitHub Desktop.
Save JasonCanCode/bcd42d169d9dc20130721b049921cbae to your computer and use it in GitHub Desktop.
import UIKit
extension UIImageView {
func setAnimationImagesWithGif(named name: String, animationDuration: TimeInterval? = nil) {
guard let bundleURL = Bundle.main.url(forResource: name, withExtension: "gif"),
let imageData = try? Data(contentsOf: bundleURL),
let source = CGImageSourceCreateWithData(imageData as CFData, nil) else {
return
}
let frameCount = CGImageSourceGetCount(source)
var animationImages: [UIImage] = []
for index in 0 ..< frameCount {
if let cgImage = CGImageSourceCreateImageAtIndex(source, index, nil) {
animationImages.append(UIImage(cgImage: cgImage))
}
}
self.animationImages = animationImages
self.animationDuration = animationDuration ?? Double(frameCount) * 0.05
sizeToFit()
// startAnimating()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment