8

I have 200px x 200px UIImageView on UICollectionViewCell that will display an image from URL. The problem is I don't know what resolution's image provided by the URL and I think it's better to resize it first before placing in UIImageView due to memory consumption.

I already use alamofire to download an image

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

I am wondering is there any method to resize it first before it use to place in UIImageView? And if any tips for download an image to save memory usage, I'd like to hear that.

Any help would be appreciated. Thank you.

4

3 回答 3

17

您可以使用过滤器:

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)

请参阅https://github.com/Alamofire/AlamofireImage#image-filters-1

对于 Swift 2 版本,请参阅此答案的先前版本

于 2016-08-25T00:30:25.167 回答
1
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
}
于 2016-08-24T23:46:02.180 回答
0

迅速 5 更新

func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
    UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}
于 2020-12-21T11:50:18.330 回答