Jasper Rosiers Jasper Rosiers - 2 years ago 139
iOS Question

resize UIImage programmatically doesn't work

I was trying to resize my image programmatically to adapt to the screen's size, but when I build my app, the image won't even show. I just see a blank screen, does anyone know what I did wrong?

This is my code (learned that from some other threads about resizing images):

class ViewControllerSport: UIViewController {

@IBOutlet weak var FotoSport: UIImageView!

let screen = UIScreen.mainScreen().bounds

override func viewDidLoad() {

FotoSport.frame = CGRect(x: 20, y: 20, width: screen.width * 0.5, height: screen.width * 0.5)
FotoSport.image = UIImage(named: "Blokker")


Answer Source

To resize image below function takes two arguments : Image and expected size.

func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size

    let widthRatio  = targetSize.width  / image.size.width
    let heightRatio = targetSize.height / image.size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
    } else {
        newSize = CGSizeMake(size.width * widthRatio,  size.height * widthRatio)

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRectMake(0, 0, newSize.width, newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    return newImage

Usage :

self.ResizeImage(UIImage(named: "MyImage.png")!, targetSize: CGSizeMake(320.0, 700.0))

Reference link :: Resize image

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download