美文网首页
iOS-GIF图播放

iOS-GIF图播放

作者: 三月望龙 | 来源:发表于2018-07-30 11:16 被阅读0次

    封装播放GIF图片的Imageview分类

    • GIF图片来源为本地或网络
    • 导入系统库: import ImageIO
    • 加载本地GIF
     func setGIFImage(gifname: String?) {
            guard let name = gifname else { return }
            guard let path = Bundle.main.path(forResource: name, ofType: nil) else { return }
            guard let data = NSData(contentsOfFile: path) else { return }
            guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else { return }
            playGIFWhit(imageSource)
        }
    
    • 加载网络GIF
     func setGIFImage(urlString: String?) {
            guard let urlStr = urlString else { return }
            guard let url = URL(string: urlStr) else { return }
            guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else { return }
            playGIFWhit(imageSource)
        }
    
    • 播放GIF图
    private func playGIFWhit(_ source: CGImageSource) {
        let keyframeCount = CGImageSourceGetCount(source)
        var images = [UIImage]()
        var duration: TimeInterval = 0
        for i in 0..<keyframeCount {
            guard let cgimage = CGImageSourceCreateImageAtIndex(source, i, nil) else { continue }
            guard let properties = CGImageSourceCopyPropertiesAtIndex(source, i, nil) ,
                let giftInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
                let keyframeDuration = giftInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber else { continue }
            images.append(UIImage(cgImage: cgimage))
            duration += keyframeDuration.doubleValue
        }
        
        self.animationImages = images
        self.animationDuration = duration
        self.animationRepeatCount = 0
        self.startAnimating()
    }
    

    相关文章

      网友评论

          本文标题:iOS-GIF图播放

          本文链接:https://www.haomeiwen.com/subject/jsnxvftx.html