Set contents of CALayer to animated GIF?

前端 未结 3 910
我在风中等你
我在风中等你 2021-01-16 10:02

Is it possible to set the contents of a CALayer to an animated GIF and have it display that animation? I know that I can set the contents to an image like so:

3条回答
  •  耶瑟儿~
    2021-01-16 10:48

    Swift 3 version, but changed to receive URL (for my own purpose).

    func createGIFAnimation(url:URL) -> CAKeyframeAnimation?{
    
        guard let src = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
        let frameCount = CGImageSourceGetCount(src)
    
        // Total loop time
        var time : Float = 0
    
        // Arrays
        var framesArray = [AnyObject]()
        var tempTimesArray = [NSNumber]()
    
        // Loop
        for i in 0..

    Important thing is written in the documentation of 'CAKeyframeAnimation':

    the first value in the array must be 0.0 and the last value must be 1.0. The array should have one more entry than appears in the values array. For example, if there are two values, there should be three key times.

    So added this line:

     timesArray.append(NSNumber(value: 1.0))
    

    And also checked in exporting as video with AVAssetExportSession.

    Please call like this:

    if let url = Bundle.main.url(forResource: "animation", withExtension: "gif"){
        let animation = createGIFAnimation(url: url)
    }
    

提交回复
热议问题