Swift 4 Gif图的解析与使用

    //分解gif图
    func resolveGifImage()->[UIImage]{
        var images:[UIImage] = []
        let gifPath = Bundle.main.path(forResource: "demo", ofType: "gif")
        if gifPath != nil{
            if let gifData = try? Data(contentsOf: URL.init(fileURLWithPath: gifPath!)){
                let gifDataSource = CGImageSourceCreateWithData(gifData as CFData, nil)
                let gifcount = CGImageSourceGetCount(gifDataSource!)
                for i in 0...gifcount - 1{
                    let imageRef = CGImageSourceCreateImageAtIndex(gifDataSource!, i, nil)
                    let image = UIImage(cgImage: imageRef!)
                    images.append(image)
                }
            }
        }
        return images
    }


    //使用
    override func viewDidLoad() {
        super.viewDidLoad()
    
    let imageView = UIImageView.init(frame: UIScreen.main.bounds)
    imageView.animationImages = resolveGifImage()
    imageView.animationDuration = 10
    imageView.animationRepeatCount = Int.max
    imageView.startAnimating()

    self.view.addSubview(imageView)
        
        // Do any additional setup after loading the view, typically from a nib.
    }

你可能感兴趣的:(Swift 4 Gif图的解析与使用)