MG–Swift – how to load local and network GIF images

  • Download code download live broadcast MGMiaoBo Download
  • There are many frameworks to load the GIF image of the network, such as SDWebImage, AFN, etc.. But how to load the local GIF, you can use webView load, of course, with the local webView loading GIF no problem, such as the UBer startup interface, you can try this way. Here is another way to load the local GIF, specifically how to look at the code:


  • 0, running effect diagram: MG--Swift - how to load local and network GIF images
    run effect diagram.Gif

  • 1, MGGIFView
/ / MGGifView.swift / / MGGIFView / / Created by Ming on 16/8/29. Copyright ming. All rights of 2016 / / reserved. / / / function: how to account for the local GIF display a picture display function: how to account for / / / GIF / / / a local picture: how to display a function for the local GIF UIKit import ImageIO import QuartzCore picture import class MGGifView: {UIView var width:CGFloat{return self.frame.size.width} var height:CGFloat{return self.frame.size.height} private var gifurl:NSURL! / / the local image into URL private var imageArr:Array< CGImage> = []; / / an array of pictures (storing each frame picture) private var timeArr:Array< NSNumber> = []; / / array (storage time of each frame picture of the time) private var totalTime:Float = 0 / / GIF / * * * loading local time animation picture GIF / func showGIFImageWithLocalName (name:String) {gifurl = NSBundle.mainBundle (name, withExtension:).URLForResource ("GIF") (self.creatKeyFrame)} / * * * access GIF images of each frame about things such as: each frame picture, each frame picture of execution private func (creatKeyFrame) * / time {let url:CFURLRef = gifurl as CFURLRef let gifSource = CGImageSourceCreateWithURL (URL, Nil) = CGImageSourceGetCount (let imageCount gifSource for I in 0..<!); imageCount {let imageRef = CGImageSourceCreateImageAtIndex (gifSource, I, nil!) / / get each frame image imageArr.append (imageRe F! Let) sourceDict = CGImageSourceCopyPropertiesAtIndex (gifSource, I, nil!) as NSDictionary! Let gifDict = sourceDict[String (kCGImagePropertyGIFDictionary)] let time = [String (kCGImagePropertyGIFUnclampedDelayTime)] gifDict! As! NSNumber// each frame of the animation time timeArr.append (time) totalTime = time.floatValue / / get the size of the picture (to) 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 (I MageWitdh.floatValue), imageHeight: CGFloat (imageHeight.floatValue))}} (self.showAnimation)} / * * * * private func fitScale (to) (imageWitdh imageWitdh:CGFloat, imageHeight:CGFloat var newWidth:CGFloat var newHeight: CGFloat) {if imageWitdh/imageHeight > width/height newWidth = width newHeight = {width/} else {newWidth (imageWitdh/imageHeight) = height/ (imageHeight/imageWitdh) newHeight = height; let point} = self.center; self.frame.size = CGSizeMake (newWidth, newHeight); self.center = point;} / * * * * private func showAnimation (animation) { Let animation = CAKeyframeAnimation (keyPath: contents) var current:Float var timeKeys:Array< = 0; 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, the controller calls
/ / / / ViewController.swift / / MGGIFView / / Created / / by Ming on 16/8/29. Copyright ming. All rights of 2016 / / reserved. / / import UIKit class ViewController: UIViewController override func (viewDidLoad) {{super.viewDidLoad (GIF View) / / load local let gifView = MGGifView (gifView.frame) = CGRectMake (0, 100, self.view.frame.width, gifView.showGIFImageWithLocalName (400) gifDemo ") view.addSubview (gifView) override func (didReceiveMemoryWarning)} {(super.didReceiveMemoryWarning) Dispose any resources that can / of be recreated.}}





  • Two, loading the network GIF picture 0, run effect diagram: MG--Swift - how to load local and network GIF images
    MG--Swift - how to load local and network GIF images
    effect diagram.Gif

MGGIFView

/ / MARK: - GIF picture / * * * load to load the network network GIF pictures WebService / func showGIFImageWithWebNetWorkUrl (url:NSURL) {let fileName = self.getMD5StringFromString (url.absoluteString / let) path filePath = (MGGifView/ + fileName +.Gif).Doc (let) Manager = NSFileManager.defaultManager (if) manager.fileExistsAtPath (filePath) {/ / self.gifurl = local read NSURL (fileURLWithPath: filePath) self.creatKeyFrame (}else) {/ / download 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; let str {/ / get string = string.cStringUsingEncoding (NSUTF8StringEncoding) / / get string length let strlen = CC_LONG (string.lengthOfBytesUsingEncoding (NSUTF8StringEncoding)) l Et digeTlen = Int (CC_MD5_DIGEST_LENGTH) / / let = UnsafeMutablePointer< brick result; CUnsignedChar>.Alloc (digeTlen) CC_MD5 (STR, strlen, result!) / / create a string variable let hash = NSMutableString (for) I in 0..< digeTlen {hash.appendFormat (%02x, result[i]) result.destroy (return) String} (format: hash as String)} / / MARK: / * * * - clear the cache clear cache method func () {let / cleanCache = folderPath ("MGGifView/").Doc (let) Manager = NSFileManager.defaultManager (do{/ fileName) is a folder fileName array let = try manager.contentsOfDirectoryAtPath (folderPath)? For name fileName in {try? Manager.removeItemAtPath (folderPath+name)} {}catch}}

External call

Import UIKit class ViewController: UIViewController override func (viewDidLoad) {{super.viewDidLoad (GIF View) / / load local let gifView = MGGifView (gifView.frame) = CGRectMake (0, 0, self.view.frame.width, self.view.frame.height) / / gifView.showGIFImageWithLocalName ("gifDemo") / URL: http://upload-images.jianshu.io/upload_images/117715-bbfe427d32237101.gif? ImageMogr2/auto-orient/strip gifView.showGIFImageWithWebNetWorkUrl (NSURL (string: http:// upload-images.jianshu.io/upload_images/117715-4e1c00e6c6ec95f9.gif imageMogr2/auto-orient/strip? ")!) view.addSubview (gifView) func (didReceiveMemoryWarning) {override} (super.didReceiveMemoryWarning) Of any resources that can / Dispose be recreated.}}

Storage classification (String)

Import UIKit extension String (CACHE) {func -> String{let cachePath = NSSearchPathForDirectoriesInDomains (NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true) return (cachePath as NSString.Last!) (.StringByAppendingPathComponent (self as NSString).PathComponents.last func doc}!) (->); String{let documentPath = NSSearchPathForDirectoriesInDomains (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true (return).Last! DocumentPath as (NSString).StringByAppendingPathComponent (self as NSString).PathComponents.Last! Func temp (->)}); String{let tempPath = NSTemporaryDirectory (return (tempPath) as NSString) (.StringByAppendingPathComponent (self as.PathComponents.Last NSString))}}



  • GitHub
project brief introduction
MGDS_Swif Funny video live
MGMiaoBo Meow broadcast live video
MGDYZB Betta live video
MGDemo N multi function collection
MGBaisi Highly imitative writing
MGSinaWeibo Highly imitative Sina
MGLoveFreshBeen An electricity supplier App
MGWeChat A small part of the WeChat function
MGTrasitionPractice Custom transitions
DBFMDemo douban
MGPlayer A video player Demo
MGCollectionView The arrangement of the annular image and petal arrangement
MGPuBuLiuDemo Waterfall flow
MGSlideViewDemo A simple point of sideslip effect, imitation QQ sideslip
MyResume A Demo to show your resume
GoodBookDemo A good book
  • 1, live radio broadcast MGMiaoBo Download
  • 2, make apparent: live App right away, can see the effect of MG--Swift - how to load local and network GIF images
    download demo 1.gif MG--Swift - how to load local and network GIF images
    introduced as funny as the funny 2.gif