swift 实现gif播放

方案1:

使用类库:https://github.com/swiftgif/SwiftGif

 

方案2;

图片路径在沙盒中:

 
  1. let filepath = NSHomeDirectory() + "/Documents/launchGif.gif"

  2. self.launchImage.ht_startGifWithFilePath(filePath: filepath)

图片放在工程中:

self.launchImage.ht_startGifWithImageName(name: "launchGif.gif")

UIImageView 扩展gif类的方法:

 
  1. extension UIImageView {

  2. //MARK:工程内gif

  3. public func ht_startGifWithImageName(name:String){

  4. guard let path = Bundle.main.path(forResource: name, ofType: "gif") else {

  5. print("SwiftGif: Source for the image does not exist")

  6. return

  7. }

  8. self.ht_startGifWithFilePath(filePath: path)

  9. }

  10. //MARK:实现动图效果

  11. public func ht_startGifWithFilePath(filePath:String) {

  12. //1.加载GIF图片,并转化为data类型

  13. guard let data = NSData(contentsOfFile: filePath) else {return}

  14. //2.从data中读取数据,转换为CGImageSource

  15. guard let imageSource = CGImageSourceCreateWithData(data, nil) else {return}

  16. let imageCount = CGImageSourceGetCount(imageSource)

  17. //3.遍历所有图片

  18. var images = [UIImage]()

  19. var totalDuration : TimeInterval = 0

  20. for i in 0..<imageCount {

  21. //3.1取出图片

  22. guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else {continue}

  23. let image = UIImage(cgImage: cgImage)

  24. images.append(image)

  25.  
  26. //3.2取出持续时间

  27. guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as? NSDictionary else {continue}

  28. guard let gifDict = properties[kCGImagePropertyGIFDictionary] as? NSDictionary else {continue}

  29. guard let frameDuration = gifDict[kCGImagePropertyGIFDelayTime] as? NSNumber else {continue}

  30. totalDuration += frameDuration.doubleValue

  31.  
  32. }

  33.  
  34. //4.设置imageview的属性

  35. self.animationImages = images

  36. self.animationDuration = totalDuration

  37. self.animationRepeatCount = 0

  38.  
  39. //5.开始播放

  40. self.startAnimating()

  41.  
  42. }

  43.  
  44. public func ht_imageStopAnimating() {

  45. self.stopAnimating()

  46. }

  47. }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值