Giter Site home page Giter Site logo

swiftygif's Introduction

Language CocoaPods Compatible Carthage compatible Build Status Pod License

SwiftyGif

High performance & easy to use Gif engine


Language Switch: 한국어

Features

  • UIImage and UIImageView extension based
  • Remote GIFs with customizable loader
  • Great CPU/Memory performances
  • Control playback
  • Allow control of display quality by using 'levelOfIntegrity'
  • Allow control CPU/memory tradeoff via 'memoryLimit'

Installation

With CocoaPods

source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
pod 'SwiftyGif'

With Carthage

Follow the usual Carthage instructions on how to add a framework to an application. When adding SwiftyGif among the frameworks listed in Cartfile, apply its syntax for GitHub repositories:

github "kirualex/SwiftyGif"

With Swift Package Manager

https://github.com/kirualex/SwiftyGif.git

How to Use

Project files

projec-file-explain

As of now, Xcode xcassets folders do not recognize .gif as images. This means you need to put your .gif outside of the assets. I recommend creating a group gif for instance.

Quick Start

SwiftyGif uses familiar UIImage and UIImageView to display gifs.

Programmaticaly

import SwiftyGif

do {
    let gif = try UIImage(gifName: "MyImage.gif")
    let imageview = UIImageView(gifImage: gif, loopCount: 3) // Will loop 3 times
    imageview.frame = view.bounds
    view.addSubview(imageview)
} catch {
    print(error)
}

Directly from nib/storyboard

@IBOutlet var myImageView : UIImageView!
...

let gif = try UIImage(gifName: "MyImage.gif")
self.myImageView.setGifImage(gif, loopCount: -1) // Will loop forever

Remote GIFs

// You can also set it with an URL pointing to your gif
let url = URL(string: "...")
let loader = UIActivityIndicatorView(style: .white)
cell.gifImageView.setGifFromURL(url, customLoader: loader)

SwiftUI

Add this UIViewRepresentable to your code.

struct AnimatedGifView: UIViewRepresentable {
    @Binding var url: URL

    func makeUIView(context: Context) -> UIImageView {
        let imageView = UIImageView(gifURL: self.url)
        imageView.contentMode = .scaleAspectFit
        return imageView
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
        uiView.setGifFromURL(self.url)
    }
}

Then to use it:

AnimatedGifView(url: Binding(get: { myModel.gif.url }, set: { _ in }))

Performances

A SwiftyGifManager can hold one or several UIImageView using the same memory pool. This allows you to tune the memory limits to your convenience. If no manager is declared, SwiftyGif will just use the SwiftyGifManager.defaultManager.

Level of integrity

Setting a lower level of integrity will allow for frame skipping, lowering both CPU and memory usage. This can be a good option if you need to preview a lot of gifs at the same time.

do {
    let gif = try UIImage(gifName: "MyImage.gif", levelOfIntegrity:0.5)
} catch {
    print(error)
}

Controls

SwiftyGif offers various controls on the current UIImageView playing your gif file.

self.myImageView.startAnimatingGif()
self.myImageView.stopAnimatingGif()
self.myImageView.showFrameAtIndexDelta(delta: Int)
self.myImageView.showFrameAtIndex(index: Int)

To allow easy use of those controls, some utility methods are provided :

self.myImageView.isAnimatingGif() // Returns whether the gif is currently playing
self.myImageView.gifImage!.framesCount() // Returns number of frames for this gif

Delegate

You can declare a SwiftyGifDelegate to receive updates on the gif lifecycle. For instance, if you want your controller MyController to act as the delegate:

override func viewDidLoad() {
        super.viewDidLoad()
        self.imageView.delegate = self
}

Then simply add an extension:

extension MyController : SwiftyGifDelegate {

    func gifURLDidFinish(sender: UIImageView) {
        print("gifURLDidFinish")
    }

    func gifURLDidFail(sender: UIImageView) {
        print("gifURLDidFail")
    }

    func gifDidStart(sender: UIImageView) {
        print("gifDidStart")
    }
    
    func gifDidLoop(sender: UIImageView) {
        print("gifDidLoop")
    }
    
    func gifDidStop(sender: UIImageView) {
        print("gifDidStop")
    }
}

Benchmark

Display 1 Image

CPU Usage(average) Memory Usage(average)
FLAnimatedImage 35% 9,5Mb
SwiftyGif 2% 18,4Mb
SwiftyGif(memoryLimit:10) 34% 9,5Mb

Display 6 Images

CPU Usage(average) Memory Usage(average)
FLAnimatedImage 65% 25,1Mb
SwiftyGif 22% 105Mb
SwiftyGif(memoryLimit:20) 45% 26Mb

Measured on an iPhone 6S, iOS 9.3.1 and Xcode 7.3.

swiftygif's People

Contributors

alak avatar alexiscreuzot avatar andrewsb avatar anilgoktas avatar ayliu-wish avatar bigearsenal avatar billypchan avatar boherna avatar bryankeller avatar bryanoltman avatar buh avatar carlo- avatar ch3cooh avatar congsun avatar giuseppepiscopo avatar grzegorzkrukowski avatar heydoy avatar jaimeagudo avatar jlnquere avatar kawolum avatar kirankunigiri avatar laurentboileau avatar legolasw avatar neil-wu avatar neobeppe avatar noblakit01 avatar nuno-vieira avatar rivera-ernesto avatar scottrhoyt avatar simdani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swiftygif's Issues

I have a problem with the use of medium

fileprivate func calculateFrameDelay(_ delaysArray:[Float],levelOfIntegrity:Float){..}

This function 219 rows. delays.count == 0 A fatal problem
if delays.count == 0 { return}

swift3

i've made swift3 full support in my fork, can you create a new branch? Then I can send you a PR

delegate

hi
is there any way to get a callback then gif stopped?
if only one loop

Suggest: Slow motion

I'm using SwiftyGif to insert a gif like a uiview background. The library works perfect, but I suggest to create a function do control the speed of the gif. it will be perfect!

Thanks

remote gifs

Hello!
What is the support for remote urls for the gif objects?

Gif from URL

What is the correct way to load a gif from a URL? Currently, I am trying to use it with AlamoFire like this

Alamofire.request(.GET, urlString).response { (request, response, data, error) in
       if let gif = UIImage(data: data!, scale:1){
            let gifManager = SwiftyGifManager(memoryLimit:20)
            self.imageView?.setGifImage(gif, manager: gifManager)
       }
}

but receive an optional unwrap fatal error in setGifImage

gif with 2 frames doesn't update

My gifs are working correctly except for the one with 2 frames.

let gifmanager = SwiftyGifManager(memoryLimit:20)
let gif4 = UIImage(gifName: "4")
self.imageView.setGifImage(gif4, manager: gifmanager)

using Xcode 8.2.1
Swift 3

Frames on Scroll goes really fast

Hello.

I've got a problem using this Library into a ScrollView. It works perfectly, the memory management is awesome, but I've got a strange bug and can't find how to fix. When I put the gifs into a CollectionView, like 3 for Row, and I scroll, when I go up back to the gifs, those are going really really fast.

Tried a lot of things, even if I set the loop count to 1, when I scroll up to the gifs that already were rendered, those goes really fast for that lonely loop.

Any solution?

Thanks.

Need help on crash

Hi,
I am using this library in one project, and I love it
But due to some reasons, it's crashing occasionally, there is no proper way to reproduce it.
I have attached some screenshots of a crash report, please someone help me on this
Thanks for your help
screen shot 2018-03-08 at 12 37 04 pm
screen shot 2018-03-08 at 12 36 30 pm

Crash: on deleteImageView(imageView: UIImageView)

the library crashes from time to time (not consistant) on

    public func deleteImageView(imageView: UIImageView){
        if let index = self.displayViews.indexOf(imageView) {
                self.displayViews.removeAtIndex(index)
                self.totalGifSize -= imageView.gifImage!.imageSize!
                if self.totalGifSize < memoryLimit && !self.haveCache {
                    self.haveCache = true
                    for imageView in self.displayViews{
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0)){
                            imageView.updateCache()
                        }
                    }
                }
        }
    }

on self.displayViews.removeAtIndex(index) line.

The case: displaying a gif when my app starts, and after login, i remove the screen with the gif form memory, althuogh i dont do any special handling of the SwiftyGif manager
Should i remove the gif when im done using it or reset the manager? what am i missing here?

thanks.

PNG

How to load Png images along with gif images

Deallocation of memory

When we remove from the view, the gif image view that was for example created with 30mb "SwiftyGifManager.init(memoryLimit: 30)", does it automatically free the space ? Many thanks, your framework is awesome!

crash

I used swift4 branch and got this crash when run an app on device
dyld: Library not loaded: @rpath/SwiftyGif.framework/SwiftyGif

memory issue

Xcode7.3 ios10.3 , when load GIF , memory will Constantly Rising until app crash

Animation is too slow?

I have try this library in my project. And saw that the gif was animating lower than it should. Please suggest me how can i speed up the animation?

gif with storyboard

Hi!
Can i use this framework with storyboard without any code? I want to present gif in LaunchScreen.storyboard file. Thanks!

Getting sizes ?

Hey ! Thanks for your work.

I need to get the size from my UIImage, but it doesnt seems to work when I'm using UIImage(gifName:). I'm doing it on your demo project. In DetailController I've added one print line :

        if let imgName = self.gifName {
            let gifImage = UIImage(gifName: imgName)
            self.imageView.setGifImage(gifImage, manager: gifManager, loopCount: -1)
            print(gifImage.size.height)
        }

I'm only getting 0... Do you have a way around ?

Crash: fatal error: Can't form Range with upperBound < lowerBound

The breakpoint hits in UIImage+SwiftyGif.swift and the app crashes with the message Crash: fatal error: Can't form Range with upperBound < lowerBound

I am trying to play a gif with 100 loops and memory limit 20. I've also included the gif file that caused the issue. It seems to be reproducable.
image

//caclulate the time when each frame should be displayed at(start at 0)
for i in 1..<delays.count{ delays[i] += delays[i-1] }

Could not determine delay times for GIF.

this appears when initialize UIImage within every convenience UIImage() or .setImage with url or Data

the one way it works if take exists .gif within UIImage(gifName: "name.gif") file - like you say "As of now, Xcode xcassets folders do not recognize .gif as images. This means you need to put your .gif oustide of the assets. I recommend creating a group gif for instance."

// here is count = 0
fileprivate func delayTimes(_ imageSource:CGImageSource) throws ->[Float] {

    let imageCount = CGImageSourceGetCount(imageSource)
    guard imageCount > 0 else {
        throw GifParseError.noImages
    }

...
}

example gif url: https://giphy.com/embed/xT39CRZ9z6lsPo66Pu

To high memory usage !

Ram usage is very high when i use good quality Gifs.
Using this attached gif as progress once the ram usage is about 100mb !
preloader

Gif animates very fast

I tried this recently in my project and saw that the gif was animating faster than it should. I cross checked in my browser and it was indeed the case.
Any idea why the speed is so fast?

I am using Swift3 with XCode 8.2

crash

crash at return (objc_getAssociatedObject(self, _imageCountKey) as! Int)

as (objc_getAssociatedObject(self, _imageCountKey) is nil

Gif Not Animating when created using storyboard

First I would like to say that everything is working as intended without storyboards, however when I tried to create an image view via storyboards the gif would just display as a still image using the following:

let gifManager = SwiftyGifManager(memoryLimit:20)
let gif = UIImage(gifName: "MyImage.gif")
self.myImageView.setGifImage(gif, manager: gifManager) 

Using Xcode 8.2.1
Swift 3

Edit: I would also for completeness like to add that i tried the following as well
self.myImageView.setGifImage(gif, manager: gifManager, loopCount:-1)

As I have said I have gotten my project to work without storyboards so I would just like to make sure this problem is known so that it can be fixed for others.

Unable to find GIF despite placed in project folder.

I am getting the error "Error : Gif file gif1.gif not found". However, gif1.gif is placed directly insider the project folder (see screenshot)

image

This is the code I am using in viewDidLoad:

    self.gifManager = SwiftyGifManager(memoryLimit: 20)
    let gif = UIImage(gifName: "gif1")
    let imageview = UIImageView(gifImage: gif, manager: gifManager)
    imageview.frame = CGRect(x: 0.0, y: 5.0, width: 400.0, height: 200.0)
    view.addSubview(imageview)

What am I doing incorrectly in my set up?

I am using XCode 8.3.3

Index of Current Frame

Is there a way to retrieve the index of the current image?

Examples:
The current image (UIImage: 000x02939) is 4 of 21.
Or gif.currentimage.index
or gif[currentimage.index]

Cannot build pod with new Swift compiler (new build system)

Hello,

When we use this pod (swift4 branch) in a project that is built with the new Swift compiler (in Xcode, in the File menu -> Project/Workspace settings -> select New build system), there is a issue when building:

unable to build node: '.../SwiftyGif/SwiftyGif.framework/Info.plist' (node is produced by multiple commands; e.g., '.../SwiftyGif/SwiftyGif.framework/Info.plist .../SwiftyGif/SwiftyGif/Info.plist' and '.../SwiftyGif/SwiftyGif.framework/Info.plist .../SwiftyGif/Info.plist')

This is due to an extra plist file present in the project.

This should be simply fixed being more specific in the podspec for source files declarations. For instance:

s.source_files = 'SwiftyGif/*{.h, .swift}'

Thanks!

Delegate doesn't get called

Hello! Recently I updated to Xcode 9 and converted code to Swift 4. After that, method gifDidLoop stopped getting called.

Crash on SwiftyGifManager function deleteImageView

Here is the following crash report:
captura de tela 2016-06-22 as 14 28 35

I'm only calling myImageView.setGifImage(...) from two places, and both are from the main thread. Any idea why this might be happening? Could it be some race condition?
It's very weird that the line pointed by the crash report is self.totalGifSize -= imageView.gifImage!.imageSize! and that the "reason" is specialized specialized Array.replaceRange<A where ...> (Range<Int>, with : A1) -> (

Thank you for this amazing project!

Compiler error "Value of optional type 'UnsafeMutableRawPointer?' not unwrapped"

In UIImage+SwiftyGif, I've got the compiler complaining that those values have to be unwrapped be cause they are optionals:
_imageSourceKey, _displayRefreshFactorKey, _imageCountKey, _displayOrderKey, _imageSizeKey, _imageDataKey

The thing is that they are instantiated with malloc that returns a forced unwrapped pointer, but as the declaration does not explicitly mark the value as being implicitly forced unwrapped, the compiler assume that they are optionals instead :/

I'm using SWIFT 4, and cocoapods 1.3.1

Delegate gifDidStop not called

I try to using delegate for imageView but only gifDidStop method delegate not called. Below is my code.

func createSplashGif() {
let gifImage = UIImage(gifName: "myVid_Splash")
let gifMyvid = SwiftyGifManager(memoryLimit:20)
self.splashImageView.delegate = self
self.splashImageView.setGifImage(gifImage, manager: gifMyvid, loopCount: 1)
}

extension MVSplashViewController: SwiftyGifDelegate {
func gifDidStop() {
print("Did Stop") // Not calling
}
}

Thanks.

gif freeze on iPad mini iOS 9.3.5

I got a wired problem.

let gif = UIImage(gifName: INspeaker_loading_2x)
gifImageView.setGifImage(gif)
gifImageView.startAnimating()

they are working well on my iPhone 6s (iOS 10.1.1),but on my iPad mini (iOS 9.3.5) the gifImageView will not play, and stay at first frame.

type "po gifImageView.isAnimating" get false in lldb.

install SwiftyGif by cocoapod with following version
SwiftyGif (3.0.0)
all code work on xcode 8.1 with swift 3.

Any help is appricated, thanks.

Never recieved call back for 'gifDidStop(sender: UIImageView)' function

Hello,

SwiftyGifDelegate not receiving updates for stopAnimatingGif() method.

Implementation Steps

Delegated in viewDidLoad
self.imageView.delegate = self

Loop count is 1
self.imageView.setGifImage(gif, manager: gifmanager, loopCount:1)

Extension for GifDelegate
extension MyController : SwiftyGifDelegate {

func gifDidStart(sender: UIImageView) {
    print("gifDidStart")
}

func gifDidLoop(sender: UIImageView) {
    print("gifDidLoop")
}

func gifDidStop(sender: UIImageView) {
    print("gifDidStop")
}

}

Not recieved call back for 'gifDidStop' function. Other delegate functions recieved call back.
Cocoapod - SwiftyGif (3.1.2)

Any help would be appreciated. Thanks

Swift 4

Hi there,

As you know it is time for Swift 4 . I saw the branch you were working on.
Is it possible to release Swift 4 version asap? Do you need any help?

whether can be stored the images in cash memory

in my app, I have lots of gif in one screen. I reduce memory size with swiftyGif but whereas I load that screen all gif load again and take a time.
so I want to store gif in cash memory.

is it possible?

Thanks help appreciated

'shared' is unavailable: Use view controller based solutions where appropriate instead. On public func isDisplayedInScreen

Hello,

I am getting the following error when load the library into my project:

Only happens when building an extension, any ideas?

../UIImageView+SwiftyGif.swift:262:71: 'shared' is unavailable: Use view controller based solutions where appropriate instead.


public func isDisplayedInScreen(_ imageView:UIView?) ->Bool{
        if (self.isHidden) {
            return false
        }
        
      let screenRect = UIScreen.main.bounds
        let viewRect = imageView!.convert(self.frame,to:UIApplication.shared.keyWindow)
        
        let intersectionRect = viewRect.intersection(screenRect);
        if (intersectionRect.isEmpty || intersectionRect.isNull) {
            return false
        }
        return (self.window != nil)
}

Gif will not play when the ImageView is positioned on the right side of the view

Dear Developers,

I'm currently having issues where the Gif will not play if the ImageView is positioned on X above 200 with 75 Width and Height. Additionally when I check its isAnimatingGif() value, it shows as true even though the Gif is not playing at all. I know it sounds weird, but I cannot find other explanation which can cause this behaviour.

Thank you.

Best Regards,

Jovial

Release notes

Hi there,

It would be great to read some release notes, as it gives some insight what is fixed/improved.
Thanks in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.