mrmike mrmike - 5 months ago 20
Swift Question

iOS Swift: How to properly scale down an image?

I'm using AlamofireImage to download and set my UIImage:

backdrop.af_setImageWithURL(downloadURL)


The image is substantially larger than what I will be displaying and so I have an issue with aliasing. How can I resize this image properly?

Results:

enter image description here

Answer

You can resize the image with any size once you have a valid UIImage:

func resizedImageWith(image: UIImage, targetSize: CGSize) -> UIImage {

    let imageSize = image.size
    let newWidth  = targetSize.width  / image.size.width
    let newHeight = targetSize.height / image.size.height
    var newSize: CGSize

    if(newWidth > newHeight) {
        newSize = CGSizeMake(imageSize.width * newHeight, imageSize.height * newHeight)
    } else {
        newSize = CGSizeMake(imageSize.width * newWidth,  imageSize.height * newWidth)
    }

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

    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)

    image.drawInRect(rect)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

For any other queries/modifications you have, refer this NShipster

Comments