Created
June 6, 2019 14:22
-
-
Save RockfordWei/292dcdbb903c5cd56868e611e61cac2b to your computer and use it in GitHub Desktop.
An asset friendly GIF library.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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