Skip to content

Instantly share code, notes, and snippets.

@RockfordWei
Created June 6, 2019 14:22
Show Gist options
  • Save RockfordWei/292dcdbb903c5cd56868e611e61cac2b to your computer and use it in GitHub Desktop.
Save RockfordWei/292dcdbb903c5cd56868e611e61cac2b to your computer and use it in GitHub Desktop.
An asset friendly GIF library.
//
// EasyGIF.swift
//
// Created by Rocky Wei on 2019-06-06.
// Copyright © 2019 Treefrog. All rights reserved.
//
import UIKit
/// An Easy GIF animation class
/// usage:
/// - load a GIF from asset:
/// ```
/// let gif = EasyGIF(named: "myGIF")
/// ```
/// - using the first frame as a static image:
/// ```
/// myImageView.image = gif.image
/// ```
/// - applying an one-time animation:
/// ```
/// gif.renderAnimation(onImageView: myView)
/// ```
public class EasyGIF {
private var frames: [UIImage] = []
/// load a GIF file from current asset by name
/// - parameter named: name of the gif in the current asset
public init?(named: String) {
guard let asset = NSDataAsset(name: named) else { return nil }
guard let source = CGImageSourceCreateWithData(asset.data as CFData, nil) else { return nil }
for i in 0 ..< CGImageSourceGetCount(source) {
if let frame = CGImageSourceCreateImageAtIndex(source, i, nil) {
let image = UIImage(cgImage: frame)
frames.append(image)
}
}
}
/// get the first frame as a static image
public var image: UIImage? {
return frames.first
}
/// directly access all the frames
public var images: [UIImage] {
return frames
}
/// perform animation on an image view
/// - parameter onImageView: the image view to render
/// - parameter duration: duration of the animation
/// - parameter repeatCount: repeatCount of the naimation
public func renderAnimation(onImageView imageView: UIImageView, duration: TimeInterval = 1, repeatCount: Int = 1) {
imageView.animationImages = images
imageView.animationDuration = duration
imageView.animationRepeatCount = repeatCount
imageView.startAnimating()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment