美文网首页iOS分享世界MG的Swift空间Swift
MG--Swift—如何加载本地和网络的GIF图片

MG--Swift—如何加载本地和网络的GIF图片

作者: Mg明明就是你 | 来源:发表于2016-08-29 16:58 被阅读1661次
    • 代码下载

    直播喵播MGMiaoBo下载

    • 前言:

      • 加载网络的GIF图片有很多框架,如:SDWebImage,AFN等。可是如何加载本地GIF,你可以用webView加载,当然用webView加载本地GIF没有问题,比如UBer的启动界面,你就可以尝试用这种方式。这里说的是另一种方式加载本地的GIF,具体如何请看代码:


    • 0、运行效果图:

    运行效果图.gif
    • 1、MGGIFView

    //  MGGifView.swift
    //  MGGIFView
    //  Created by ming on 16/8/29.
    //  Copyright © 2016年 ming. All rights reserved.
    
    /// 功能: 如何占展示一张本地的GIF图片
    /// 功能: 如何占展示一张本地的GIF图片
    /// 功能: 如何占展示一张本地的GIF图片
    
    import UIKit
    import ImageIO
    import QuartzCore
    
    class MGGifView: UIView {
    
        var width:CGFloat{return self.frame.size.width}
        var height:CGFloat{return self.frame.size.height}
        private var gifurl:NSURL! // 把本地图片转化成URL
        private var imageArr:Array<CGImage> = [] // 图片数组(存放每一帧的图片)
        private var timeArr:Array<NSNumber> = [] // 时间数组(存放每一帧的图片的时间)
        private var totalTime:Float = 0 // gif动画时间
        /**
        *  加载本地GIF图片
        */
        func showGIFImageWithLocalName(name:String) {
            gifurl = NSBundle.mainBundle().URLForResource(name, withExtension: "gif")
            self.creatKeyFrame()
        }
    
        
        /**
        *  获取GIF图片的每一帧 有关的东西  比如:每一帧的图片、每一帧的图片执行的时间
        */
        private func creatKeyFrame() {
            let url:CFURLRef = gifurl as CFURLRef
            let gifSource = CGImageSourceCreateWithURL(url, nil)
            let imageCount = CGImageSourceGetCount(gifSource!)
            
            for i in 0..<imageCount {
                let imageRef = CGImageSourceCreateImageAtIndex(gifSource!, i, nil) // 取得每一帧的图片
                imageArr.append(imageRef!)
                
    
                let sourceDict = CGImageSourceCopyPropertiesAtIndex(gifSource!, i, nil) as NSDictionary!
                let gifDict = sourceDict[String(kCGImagePropertyGIFDictionary)]
                let time = gifDict![String(kCGImagePropertyGIFUnclampedDelayTime)] as! NSNumber// 每一帧的动画时间
                timeArr.append(time)
                totalTime += time.floatValue
                
                // 获取图片的尺寸 (适应)
                let imageWitdh = sourceDict[String(kCGImagePropertyPixelWidth)] as! NSNumber
                let imageHeight = sourceDict[String(kCGImagePropertyPixelHeight)] as! NSNumber
                if ((imageWitdh.floatValue)/(imageHeight.floatValue) != Float((width)/(height))) {
                    self.fitScale(imageWitdh: CGFloat(imageWitdh.floatValue), imageHeight: CGFloat(imageHeight.floatValue))
                }
            }
            
            self.showAnimation()
        }
        
        /**
        *  (适应)
        */
        private func fitScale(imageWitdh imageWitdh:CGFloat, imageHeight:CGFloat) {
            var newWidth:CGFloat
            var newHeight:CGFloat
            if imageWitdh/imageHeight > width/height {
                newWidth = width
                newHeight = width/(imageWitdh/imageHeight)
            } else {
                newWidth = height/(imageHeight/imageWitdh)
                newHeight = height;
            }
            let point = self.center;
            self.frame.size = CGSizeMake(newWidth, newHeight);
            self.center = point;
        }
        
        /**
        *  展示动画
        */
        private func showAnimation() {
            let animation = CAKeyframeAnimation(keyPath: "contents")
            var current:Float = 0
            var timeKeys:Array<NSNumber> = []
            
            for time in timeArr {
                timeKeys.append(NSNumber(float: current/totalTime))
                current += time.floatValue
            }
            animation.keyTimes = timeKeys
            animation.values = imageArr
            animation.repeatCount = HUGE;
            animation.duration = NSTimeInterval(totalTime)
            animation.removedOnCompletion = false
            self.layer .addAnimation(animation, forKey: "MGGifView")
        }
    }
    

    • 2、在控制器中调用

    //
    //  ViewController.swift
    //  MGGIFView
    //
    //  Created by ming on 16/8/29.
    //  Copyright © 2016年 ming. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            
            // 加载本地GIF 的View
            let gifView = MGGifView()
            gifView.frame = CGRectMake(0, 100, self.view.frame.width, 400)
            gifView.showGIFImageWithLocalName("gifDemo")
            view.addSubview(gifView)
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }```
    ***
    ***
    ***
    ***
    ***
    
    - #二、加载网络GIF图片
    >#0、运行效果图:
    ![](https://img.haomeiwen.com/i117715/4e1c00e6c6ec95f9.gif?imageMogr2/auto-orient/strip)
    ![运行效果图.gif](https://img.haomeiwen.com/i1429890/4bd3ab70fe9b6555.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    
    > - ###MGGIFView
    
    

    // MARK: - 加载网络GIF图片
    /**
    * 加载网络GIF图片WebService
    */
    func showGIFImageWithWebNetWorkUrl(url:NSURL) {
    let fileName = self.getMD5StringFromString(url.absoluteString)
    // 路径
    let filePath = ("MGGifView/" + fileName + ".gif").doc()

        let manager = NSFileManager.defaultManager()
        if manager.fileExistsAtPath(filePath) {  // 本地读取
            self.gifurl = NSURL(fileURLWithPath: filePath)
            self.creatKeyFrame()
        }else { // 下载
            dispatch_sync(dispatch_get_global_queue(0, 0), { () -> Void in
                let session = NSURLSession.sharedSession()
                
                let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in
                    print(error)
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        data?.writeToFile(filePath, atomically: true)
                        self.gifurl = NSURL(fileURLWithPath: filePath)
                        self.creatKeyFrame()
                    })
                }
                 task.resume()
            })
           
        }
    }
    
    /**
    *  string -> MD5
    */
    private func getMD5StringFromString(string:String) -> String {
        // 获取string
        let str = string.cStringUsingEncoding(NSUTF8StringEncoding)
        // 获取string 的长度
        let strlen = CC_LONG(string.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let digeTlen = Int(CC_MD5_DIGEST_LENGTH) // 强砖
        let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digeTlen)
        CC_MD5(str!,strlen,result)
        
        // 创建一个可变的字符串
        let hash = NSMutableString()
        for i in 0..<digeTlen {
            hash.appendFormat("%02x",result[i])
        }
        result.destroy()
        
        return String(format: hash as String)
    }
    
    // MARK: - 清除缓存
    /**
    *  清除缓存方法
    */
    func cleanCache() {
        let folderPath = ("MGGifView/").doc()
        let manager = NSFileManager.defaultManager()
        
        do{
            // fileName是一个文件夹数组
            let fileName = try? manager.contentsOfDirectoryAtPath(folderPath)
            for name in fileName! {
                try? manager.removeItemAtPath(folderPath+name)
            }
        }catch {
            
        }
    }
    
    ***
    
    > ###外部调用
    
    

    import UIKit

    class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载本地GIF 的View
        let gifView = MGGifView()
        gifView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
    

    // gifView.showGIFImageWithLocalName("gifDemo")

        // 网址: https://img.haomeiwen.com/i117715/bbfe427d32237101.gif?imageMogr2/auto-orient/strip
        gifView.showGIFImageWithWebNetWorkUrl(NSURL(string:"https://img.haomeiwen.com/i117715/4e1c00e6c6ec95f9.gif?imageMogr2/auto-orient/strip")!)
        view.addSubview(gifView)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    }

    ***
    
    > ###存储的分类(String)
    
    

    import UIKit

    extension String
    {
    func cache() -> String{
    let cachePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
    return (cachePath as NSString).stringByAppendingPathComponent((self as NSString).pathComponents.last!)
    }

    func doc() -> String{
        let documentPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
        return (documentPath as NSString).stringByAppendingPathComponent((self as NSString).pathComponents
        .last!)
    }
    
    func temp() -> String{
        let tempPath = NSTemporaryDirectory()
        return (tempPath as NSString).stringByAppendingPathComponent((self as NSString).pathComponents
            .last!)
    }
    

    }```




    • github

    | 项目 | 简介 |
    | : | : |
    | MGDS_Swif | 逗视视频直播 |
    | MGMiaoBo | 喵播视频直播 |
    | MGDYZB | 斗鱼视频直播 |
    | MGDemo | n多小功能合集 |
    | MGBaisi | 高度仿写百思 |
    | MGSinaWeibo | 高度仿写Sina |
    | MGLoveFreshBeen | 一款电商App |
    | MGWeChat | 小部分实现微信功能 |
    | MGTrasitionPractice | 自定义转场练习 |
    | DBFMDemo | 豆瓣电台 |
    | MGPlayer | 一个播放视频的Demo |
    | MGCollectionView | 环形图片排布以及花瓣形排布 |
    | MGPuBuLiuDemo | 瀑布流--商品展 |
    | MGSlideViewDemo | 一个简单点的侧滑效果,仿QQ侧滑 |
    | MyResume | 一个展示自己个人简历的Demo |
    | GoodBookDemo | 好书 |

    逗视介绍1.gif
    逗视介绍2.gif

    相关文章

      网友评论

      本文标题:MG--Swift—如何加载本地和网络的GIF图片

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