mrmike mrmike - 6 months ago 30
Swift Question

iOS Swift: How to properly scale down an image?

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


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?


enter image description here


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)


    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    return newImage

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