最近項目中須要用到網絡圖片加載,在網上找了不少圖片加載的文章,不過感受都不怎麼方便。後來找到 AlamofireImage這個庫,使用起來很是簡單,readme也很是清晰,記錄一下使用過程,但願幫到須要的人,本文代碼使用的是AlamofireImage 3.3版本。
//使用cocoapods導入 pod 'AlamofireImage', '~> 3.3'
真的很是簡單,兩行代碼搞定(記得要 import AlamofireImage)git
let imageView = UIImageView(frame: frame) let url = URL(string: "https://httpbin.org/image/png")! imageView.af_setImage(withURL: url)
設置默認圖片:github
let imageView = UIImageView(frame: frame) let url = URL(string: "https://httpbin.org/image/png")! let placeholderImage = UIImage(named: "placeholder")! imageView.af_setImage(withURL: url, placeholderImage: placeholderImage)
對圖片進行縮放:swift
let image = UIImage(named: "unicorn")! let size = CGSize(width: 100.0, height: 100.0) let scaledImage = image.af_imageScaled(to: size) let aspectScaledToFitImage = image.af_imageAspectScaled(toFit: size) let aspectScaledToFillImage = image.af_imageAspectScaled(toFill: size)
圓形圖片:緩存
let image = UIImage(named: "unicorn")! let radius: CGFloat = 20.0 let roundedImage = image.af_imageRounded(withCornerRadius: radius) let circularImage = image.af_imageRoundedIntoCircle()
雖然使用AlamofireImage加載圖片已經很是簡單,不過每次須要加載網絡圖片都須要導包,而且圖片要求傳URL,因此咱們能夠作一些簡單的擴展。網絡
import AlamofireImage extension UIImageView{ func setImageUrl(_ string : String?) { if(string != nil){ let url = URL(string: string!)! self.af_setImage(withURL: url) } } } //使用 userImgImage.setImageUrl("https://httpbin.org/image/png")
在AlamofireImage的readme中,提到一下用法,其中responseImage已經被廢棄,可能沒法使用。在源碼中能夠看到@discardableResult
標記url
Alamofire.request("https://httpbin.org/image/png").responseImage { response in debugPrint(response) print(response.request) print(response.response) debugPrint(response.result) if let image = response.result.value { print("image downloaded: \(image)") } }