扩展UIImage和UIImageView

31. January 2016 笔记 0

//

//  Extension.swift

import UIKit

import SDWebImage

extension UIImage {

func resizeToSize(size:CGSize) -> UIImage{ //重新绘制图片

UIGraphicsBeginImageContextWithOptions(size, false, 0)

drawInRect(CGRectMake(0, 0, size.width, size.height))

let newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext()

return newImage

}

}

extension UIImageView{

func setResizeImageWith1(URLString:String,width:CGFloat){

let URL = NSURL(string: URLString)

let key = SDWebImageManager.sharedManager().cacheKeyForURL(URL) ?? “”

if var cacheImage = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key){ //从缓存中下载图片

if cacheImage.size.width > width {

let size = CGSizeMake(width,cacheImage.size.height * (width/cacheImage.size.width))

cacheImage = cacheImage.resizeToSize(size)

}

self.image = cacheImage

}else{ //缓存中不存在,从网络中下载图片

SDWebImageDownloader.sharedDownloader().downloadImageWithURL(URL, options: .AllowInvalidSSLCertificates, progress: nil, completed:{

(var image,data,error,result) -> Void in

if image != nil && image.size.width > width {

let size = CGSizeMake(width, image.size.height * (width/image.size.width)) //定义图片的尺寸

image = image.resizeToSize(size)

}

self.image = image

})

}

}

}


Leave a Reply

Your email address will not be published. Required fields are marked *