🌠 A small UIImage extension with gif support

Last update: Jun 21, 2022

⚠️ UNMAINTAINED ⚠️

This library is no longer maintained. I recommend using Gifu instead.


SwiftGif Swift 3.0 Carthage compatible CocoaPods License MIT Build Status

A small UIImage extension with gif support.

Demo gif

Usage

import SwiftGifOrigin

// An animated UIImage
let jeremyGif = UIImage.gif(name: "jeremy")

// A UIImageView with async loading
let imageView = UIImageView()
imageView.loadGif(name: "jeremy")

// A UIImageView with async loading from asset catalog(from iOS9)
let imageView = UIImageView()
imageView.loadGif(asset: "jeremy")

Installation

CocoaPods

Install CocoaPods with the following command:

gem install cocoapods

Integrate SwiftGif into your Xcode project by creating a Podfile:

platform :ios, '9.0'
use_frameworks!

target '
   
   
    
    '
   
    do
    pod 'SwiftGifOrigin', '~> 1.7.0'
end

Run pod install to build your dependencies.

Carthage

Install Carthage with Homebrew using the following command:

brew update
brew install carthage

Add the following line to your Cartfile to add SwiftGif:

1.7.0 ">
github "bahlo/SwiftGif" ~> 1.7.0

Run carthage update to build the framework and drag the built SwiftGif.framework into your Xcode project.

How does it work?

Easy, it does the following:

  1. Find out the duration of every frame
  2. Find the greatest common divisor
  3. Add frames accordingly to the greatest common divisor to an array
  4. Create an animated UIImage with the frames

Testing

$ xcodebuild \
  -project SwiftGif.xcodeproj \
  -scheme SwiftGif \
  -sdk iphonesimulator \
  -destination "platform=iOS Simulator,name=iPhone 8" \
  build test \
  CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY=""

Inspiration

This project is heavily inspired by uiimage-from-animated-gif. Kudos to @mayoff. πŸ‘

License

This repository is licensed under the MIT license, more under LICENSE.

GitHub

https://github.com/swiftgif/SwiftGif
Comments
  • 1. How to install by pod for swift3 ??

    I cannot install SwiftGif for swift3.

    My Podfile is ..

    pod 'SwiftGifOrigin', '~> 1.6'
    

    But I get the following error.

    Analyzing dependencies
    [!] Unable to satisfy the following requirements:
    
    - `SwiftGifOrigin (~> 1.6)` required by `Podfile`
    - `SwiftGifOrigin (~> 1.6)` required by `Podfile`
    
    None of your spec sources contain a spec satisfying the dependency: `SwiftGifOrigin (~> 1.6)`.
    
    You have either:
     * out-of-date source repos which you can update with `pod repo update`.
     * mistyped the name or version.
     * not added the source repo that hosts the Podspec to your Podfile.
    
    Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by default.
    

    I run pod repo update, but I get the same error again.

    How can I use SwiftGif??

    Reviewed by HirotoIchinose at 2016-09-19 09:21
  • 2. Made calling SwiftGif Easier

    Now you can call SwiftGif only by knowing the gif files name: UIImage.gifWithName("jeremy")

    or can call the old method if prefered: UIImage.gifWithData(imageData!)

    Reviewed by goktugyil at 2015-10-12 18:43
  • 3. Compile Fail with Xcode 6.3 Final

    let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) is giving an error = "Cannot invoke 'CGImageSourceCopyPropertiesAtIndex' with an argument list of type 'CGImageSourceRef,Uint,nil)'

    Reviewed by kbirand at 2015-04-14 10:40
  • 4. Achieve Carthage compatibility by compiling source file in target's build phase

    Hey, @bahlo

    Great framework here! Very useful for an app I'm working on. I'm using Carthage in my app and was unfortunately having a problem with integrating SwiftGif. Based on #48, it seems that others have also had similar problems with using Carthage to integrate SwiftGif.

    Anyway, this PR should fix the issue. Feel free to test it out and merge if you like.

    Reviewed by tforzaglia at 2017-05-10 00:27
  • 5. How to pause temporarily the gif?

    Hi Bahlo, I've just took a look on your library. Everything works amazingly, but I am in stuck with a problem. How to pause temporarily the gif? I want pause and resume it for some reason (like music play, pause...)

    Thanks very much and wait for your reply.

    Reviewed by peihsendoyle at 2016-09-21 12:59
  • 6. Add Carthage support

    Hello,

    I've added Carthage support for this project I started using. I know it says "Carthage compatible" but it actually didn't provide a shared Framework scheme. This is the error you'd get if you tried using it:

    $  carthage update
    *** Fetching SwiftGif
    *** Checking out SwiftGif at "v1.5.1"
    *** xcodebuild output can be found in /var/folders/tk/cw93k7v928qf21kppt47d_380000gn/T/carthage-xcodebuild.QXYO0e.log
    *** Skipped building SwiftGif due to the error:
    Dependency "SwiftGif" has no shared framework schemes
    
    If you believe this to be an error, please file an issue with the maintainers at https://github.com/bahlo/SwiftGif/issues/new
    

    Here is what I've done:

    • Moved the code from "SwiftGifCommon" into a dedicated "SwiftGif" folder and created the framework scheme
    • Renamed the "SwiftGif" target into "SwiftGifDemo"
    • I updated the path in the podspec as well and bumped the version number so you can tag / push

    Hopefully the travis build should still pass. Let me know what you think about this :smile:

    Reviewed by Palleas at 2015-11-29 17:10
  • 7. Carthage problem

    Hello,

    When I pull the framework with a carthage update (github "bahlo/SwiftGif" ~> 1.6.1), I can import it normally with "import SwiftGif" but I can't access to any methods of it...

    Am I doing wrong or it's a framework issue? Thank you.

    Reviewed by VTCoco at 2016-12-09 11:04
  • 8. Crashes with invalid GIF data

    Hi, trying to load invalid data as a GIF crashes this code with EXC_BAD_ACCESS. This is due to the unsafe code in delayForImageAtIndex(). Proper checks should be in place and the UIImage.gifWithData() should throw / return nil if invalid data was handed in.

    As a quick hack, the following is how I made this 'work' (= not crash):

        class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double {
            var delay = 0.1
    
            guard let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? NSDictionary,
                gifProperties = cfProperties[kCGImagePropertyGIFDictionary as NSString] as? NSDictionary else {
                    return delay
            }
    
            var delayTime = gifProperties[kCGImagePropertyGIFUnclampedDelayTime as NSString]
    
            if delayTime?.doubleValue == 0.0 {
                delayTime = gifProperties[kCGImagePropertyGIFDelayTime as NSString]
            }
    
            if let delayTime = delayTime {
                delay = delayTime.doubleValue
            }
    
            if delay < 0.1 {
                delay = 0.1 // Make sure they're not too fast
            }
    
            return delay
        }
    

    Also, building for the device, I get the linker error:

    ld: framework not found SwiftGifOrigin for architecture arm64
    
    • Matti
    Reviewed by qvik at 2015-12-09 13:32
  • 9. Drop the setup

    // jeremy.gif
    var url = NSBundle.mainBundle().URLForResource("jeremy", withExtension: "gif")
    var imageData = NSData(contentsOfURL: url)
    
    // Returns an animated UIImage
    UIImage.animatedImageWithData(imageData)
    

    This uses too many lines to setup the gif. It could have been only:

     UIImage.withGifName("jeremy")
    

    I might do this in the future when I have time

    Reviewed by goktugyil at 2015-09-15 19:09
  • 10. Tests fail in Xcode6-Beta5

    When running the tests in Xcode6-Beta5, they fail when trying to load the test gif:

    let cfImageData = imageData! as CFDataRef
    

    Throws fatal error: unexpectedly found nil while unwrapping an Optional value; this looks to be caused by

    imageData = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("test", withExtension: "gif"))
    

    Returning nil. I've tried various ways of loading images, but can't seem to get the resources to load (UIImage named etc all fail).

    Thanks for the awesome library!

    Reviewed by gavinbunney at 2014-08-12 06:08
  • 11. Update to swift3?

    Hey,

    Just wanted to know if you're planning to update it for Swift3 or if it's abandonned ! So I can look for another third party option ! It would be a shame, it's the more practical and the lightest one !

    Reviewed by petaire92 at 2016-08-22 15:52
  • 12. added gif into NSTextAttachment, but not animated

    hi, i loaded success gif image into my attribute string, but it can not animate, it's hard to me to know the problem

    let attachment = NSTextAttachment()
                                        attachment.image = UIImage.gif(url: getEmojiUrl(name: data.Data))
                                        attachment.bounds = CGRect(x: 0, y: ((UIFont.systemFont(ofSize: 16).capHeight) - 28).rounded() / 2, width: 28, height: 28)
                                        let replacement = NSAttributedString(attachment: attachment)
                                        attributedString.replaceCharacters(in: aMatch.range, with: replacement)
    

    Screen Shot 2020-06-11 at 15 22 08

    this is sample link i loaded https://devlink.vedax.ai/images/emotions/cry.gif

    Reviewed by fukemy at 2020-06-11 08:22
  • 13. Unknown class GIFImageView in Interface Builder file.

    So in storyboard I have an imageView, did set its class as "GIFImageView". When running app, the error in title is displayed.

    Library installed as pod pod 'SwiftGifOrigin', '~> 1.7.0'

    I also did a global search in the project Pods folder, and there are no results for a word "GIFImageView" - the class is not found in the library.

    This is what I see:

    Screenshot 2019-12-30 at 17 37 28

    Reviewed by dxshindeo at 2019-12-30 15:39
  • 14. iOS 13 support for traitCollection.userInterfaceStyle (Dark mode)

    First of all, awesome extension!

    I'm using SwiftGif to display animations along the UI, but with iOS 13 I found some of my animations are not displaying correctly on DarkMode, so I'd like to have trait variations as we have with UIColor:

    static var customAccent: UIColor {
        if #available(iOS 13, *) {
            return UIColor { (traitCollection: UITraitCollection) -> UIColor in
                if traitCollection.userInterfaceStyle == .dark {
                    return MaterialUI.orange300
                } else {
                    return MaterialUI.orange600
                }
            }
        } else {
            return MaterialUI.orange600
        }
    }
    

    I can make something similar with UIImage using this code (below), but I cannot get it to work with the Gifs.

    extension UIImage {
        /// Creates a dynamic image that supports displaying a different image asset when dark mode is active.
        static func dynamicImageWith(
            light makeLight: @autoclosure () -> UIImage,
            dark makeDark: @autoclosure () -> UIImage
        ) -> UIImage {
            let image = UITraitCollection(userInterfaceStyle: .light).makeImage(makeLight())
    
            image.imageAsset?.register(makeDark(), with: UITraitCollection(userInterfaceStyle: .dark))
    
            return image
        }
    }
    
    extension UITraitCollection {
        /// Creates the provided image with traits from the receiver.
        func makeImage(_ makeImage: @autoclosure () -> UIImage) -> UIImage {
            var image: UIImage!
            performAsCurrent {
                image = makeImage()
            }
            return image
        }
    }
    

    Anyone have any idea on how to solve the problem?

    Reviewed by JorgeFrias at 2019-11-25 18:22
Async GIF image decoder and Image viewer supporting play GIF images. It just use very less memory.
Async GIF image decoder and Image viewer supporting play GIF images. It just use very less memory.

YLGIFImage Asynchronized GIF image class and Image viewer supporting play/stop GIF images. It just use very less memory. Following GIF usually will co

Jun 15, 2022
High-performance animated GIF support for iOS in Swift
High-performance animated GIF support for iOS in Swift

Gifu adds protocol-based, performance-aware animated GIF support to UIKit. (It's also a prefecture in Japan). Install Swift Package Manager Add the fo

Jun 25, 2022
Performant animated GIF engine for iOS
Performant animated GIF engine for iOS

FLAnimatedImage is a performant animated GIF engine for iOS: Plays multiple GIFs simultaneously with a playback speed comparable to desktop browsers H

Jun 16, 2022
XAnimatedImage is a performant animated GIF engine for iOS written in Swift based on FLAnimatedImage
XAnimatedImage is a performant animated GIF engine for iOS written in Swift based on FLAnimatedImage

XAnimatedImage is a performant animated GIF engine for iOS written in Swift based on FLAnimatedImage. An illustration is shown below: Features Plays m

May 5, 2022
Image framework for iOS to display/encode/decode animated WebP, APNG, GIF, and more.
Image framework for iOS to display/encode/decode animated WebP, APNG, GIF, and more.

YYImage Image framework for iOS to display/encode/decode animated WebP, APNG, GIF, and more. (It's a component of YYKit) Features Display/encode/decod

Jun 21, 2022
An animated gif & apng engine for iOS in Swift. Have a great performance on memory and cpu usage.

Features Small but complete, only200lines of code. Allow to control display quality, memory usage, loop time and display progress. Have a great perfor

Jun 18, 2022
SwiftyGif - High performance & easy to use Gif engine
 SwiftyGif - High performance & easy to use Gif engine

SwiftyGif High performance & easy to use Gif engine Features UIImage and UIImageView extension based Remote GIFs with customizable loader Great CPU/Me

Jun 23, 2022
🌠 A small UIImage extension with gif support
🌠 A small UIImage extension with gif support

?? A small UIImage extension with gif support

Jun 21, 2022
πŸ”₯ πŸ”₯ πŸ”₯Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

?? ?? ??Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

Mar 2, 2022
Complete Animated GIF Support for iOS, with Functions, NSJSONSerialization-style Class, and (Optional) UIImage Swizzling
Complete Animated GIF Support for iOS, with Functions, NSJSONSerialization-style Class, and (Optional) UIImage Swizzling

AnimatedGIFImageSerialization This library is no longer maintained. In iOS 13+ and macOS 10.15+, use CGAnimateImageAtURLWithBlock instead. AnimatedGIF

May 16, 2022
Async GIF image decoder and Image viewer supporting play GIF images. It just use very less memory.
Async GIF image decoder and Image viewer supporting play GIF images. It just use very less memory.

YLGIFImage Asynchronized GIF image class and Image viewer supporting play/stop GIF images. It just use very less memory. Following GIF usually will co

Jun 15, 2022
An NSFW image detector for Swift built as an extension on UIImage.

Swift_NSFW_Detector An NSFW image detector for Swift built as an extension on UIImage. If you've ever allowed users to share images you are probably w

Mar 26, 2022
Gifu adds protocol-based, performance-aware animated GIF support to UIKit.
Gifu adds protocol-based, performance-aware animated GIF support to UIKit.

Gifu adds protocol-based, performance-aware animated GIF support to UIKit. (It's also a prefecture in Japan). Install Swift Package Manager Add the fo

Jun 15, 2022
High-performance animated GIF support for iOS in Swift
High-performance animated GIF support for iOS in Swift

Gifu adds protocol-based, performance-aware animated GIF support to UIKit. (It's also a prefecture in Japan). Install Swift Package Manager Add the fo

Jun 21, 2021
High-performance animated GIF support for iOS in Swift
High-performance animated GIF support for iOS in Swift

Gifu adds protocol-based, performance-aware animated GIF support to UIKit. (It's also a prefecture in Japan). Install Swift Package Manager Add the fo

Jun 25, 2022
Custom emoji rendering library for iOS apps with support for GIF & still images
Custom emoji rendering library for iOS apps with support for GIF & still images

Custom emoji rendering library for iOS apps with support for GIF & still images - plug-in extension for UITextView - performance, cache βœ… - Made with ?? by @GetStream

Apr 2, 2022
A tool support convert image gif to gif3d
A tool support convert image gif to gif3d

Trick convert gif to gif3d using Swift Features Simple way to convert gif to gif3d Change background Change size eraser tool How to work Add a layer w

Nov 10, 2021
High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton, Promise and more.

SwiftyUI High performance and lightweight UIView, UIImage, UIImageView, UIlabel, UIButton and more. Features SwiftyView GPU rendering Image and Color

May 31, 2022
A tool to calculate the color ratio of UIImage in iOS.
A tool to calculate the color ratio of UIImage in iOS.

UIImageColorRatio A tool to calculate the color ratio of UIImage in iOS. How to use UIImageColorRatio Get the color ratio of UIImage. let image = ...

Feb 24, 2022
TextDrawer, is a UIView allows you to add text, with gesture, on UIView, or UIImage
TextDrawer, is a UIView allows you to add text, with gesture, on UIView, or UIImage

TextDrawer TextDrawer, is a UIView allows you to add text, with gesture, on UIView, or UIImage. About Annotating Images TextDrawer is the easiest way

Mar 5, 2022