最近项目中需要用到网络图片加载,在网上找了很多图片加载的文章,不过感觉都不怎么方便。后来找到 AlamofireImage这个库,使用起来非常简单,readme也非常清晰,记录一下使用过程,希望帮到需要的人,本文代码使用的是AlamofireImage 3.3版本。
优点
导入
//使用cocoapods导入 pod 'AlamofireImage','~> 3.3'
使用
真的非常简单,两行代码搞定(记得要 import AlamofireImage)
let imageView = UIImageView(frame: frame) let url = URL(string: "https://httpbin.org/image/png")! imageView.af_setImage(withURL: url)
设置默认图片:
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)
对图片进行缩放:
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
标记
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)") } }