Resize Image Using AlamofireImage

I have 200px x 200px UIImageViewon UICollectionViewCellwhich will display an image from a URL. The problem is that I don’t know which resolution image is provided by the URL, and I think it’s better to resize it first before putting it in UIImageViewdue to memory consumption.

I already use alamofire to upload the image

let url = NSURL(string: "http:\(product.picUrl)")
self.imgProductItem.af_setImageWithURL(url!, placeholderImage: UIImage(named: "app_default-resize"))

I am wondering if there is any method for changing it first before using it in UIImageView? And if there are any tips on loading an image to save memory, I would love to hear that.

Any help would be greatly appreciated. Thank.

+4
source share
2 answers

You can use filters:

let url = URL(string: ...)!
let placeholder = UIImage(named: "app_default-resize")
let filter = AspectScaledToFillSizeFilter(size: imageView.frame.size)
imageView.af_setImage(withURL: url, placeholderImage: placeholder, filter: filter)

See https://github.com/Alamofire/AlamofireImage#image-filters-1 .

For Swift 2, see the previous version of this answer .

+9
source
func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {

    let rect = CGRectMake(0, 0, targetSize.width, targetSize.height)

    UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0)
    image.drawInRect(rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}
0
source

Source: https://habr.com/ru/post/1652394/


All Articles