How do set a width and height of an Image in Swift
Asked Answered
T

5

39

New to Swift and iOS programming in general. I couldn't figure out how to set a width and height of an image.
For example,

  let backgroundImage = UIImage(named: "background.png")

Thanks

Twila answered 12/7, 2014 at 3:8 Comment(1)
Why not set the UIImageView's frame size instead? Unless you truly want to draw a brand new UIImage using a context.Siward
I
30

My suggestion is.

Instead of set size of image you should set size of UIImageView and then put this image on it so, size of image will be display as per your requirement.

Such like,

var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150)); // set as you want
var image = UIImage(named: "myImage.png");
imageView.image = image;
self.view.addSubview(imageView);
Insurmountable answered 12/7, 2014 at 3:14 Comment(4)
What if your imageView is already declared and has width and height constraints? How do you change it then?Emlyn
imageView.frame = CGRect(x: 100, y: 150, width: 150, height: 150)Insurmountable
this didn't work for me because it conflicts with the Auto Layout constraints the imageView has for width and height.Emlyn
To make the suggestion work in Swift 3 or later, replace the first line with: var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))Possing
T
19

You have this code, this code set width and height and save the same position.

/**
Resize UIImageView
:param: UImage
:param: new size CGSize
:return: new UImage rezised
*/
    func imageResize (#image:UIImage, sizeChange:CGSize)-> UIImage{

        let hasAlpha = true
        let scale: CGFloat = 0.0 // Use scale factor of main screen

        // Create a Drawing Environment (which will render to a bitmap image, later)
        UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)

        image.drawInRect(CGRect(origin: CGPointZero, size: sizeChange))

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()

        // Clean up the Drawing Environment (created above)
        UIGraphicsEndImageContext()

        return scaledImage
    }

     let size = CGSizeMake(100, 150)

    myImageView.image! = imageResize(myImageView.image!,sizeChange: size)

Work in viewDidLoad or refresh "reloadInputViews()" your UIImageView ;-)

**

EDIT

**

Hi create this extends if you want.

Create File Extends.Swift and add this code (add import foundation where you want change height)

/**
    Extension UIView
*/
extension UIView {
    /**
    Set x Position

    :param: x CGFloat
    */
    func setX(#x:CGFloat) {
        var frame:CGRect = self.frame
        frame.origin.x = x
        self.frame = frame
    }
    /**
    Set y Position

    :param: y CGFloat
    */
    func setY(#y:CGFloat) {
        var frame:CGRect = self.frame
        frame.origin.y = y
        self.frame = frame
    }
    /**
    Set Width

    :param: width CGFloat
    */
    func setWidth(#width:CGFloat) {
        var frame:CGRect = self.frame
        frame.size.width = width
        self.frame = frame
    }
    /**
    Set Height

    :param: height CGFloat
    */
    func setHeight(#height:CGFloat) {
        var frame:CGRect = self.frame
        frame.size.height = height
        self.frame = frame
    }
}

For Use (inherits Of UIView)

inheritsOfUIView.setHeight(height: 100)
button.setHeight(height: 100)
view.setHeight(height: 100)
Tacklind answered 20/1, 2015 at 18:11 Comment(0)
Q
19

Swift 3.0 version (from @YannickSteph)

extension UIImage {

    func imageResize (sizeChange:CGSize)-> UIImage{

        let hasAlpha = true
        let scale: CGFloat = 0.0 // Use scale factor of main screen

        UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
        self.draw(in: CGRect(origin: CGPoint.zero, size: sizeChange))

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        return scaledImage!
    }

}
Quickel answered 24/10, 2016 at 7:22 Comment(1)
Put the height and width in a CGSize object and pass it to the imageResize method while calling it.Curtcurtail
M
11

if you want to keep the aspect ratio, here is an extension method for Swift 3 :

import UIKit

extension UIImage {

    func resize(maxWidthHeight : Double)-> UIImage? {

        let actualHeight = Double(size.height)
        let actualWidth = Double(size.width)
        var maxWidth = 0.0
        var maxHeight = 0.0

        if actualWidth > actualHeight {
            maxWidth = maxWidthHeight
            let per = (100.0 * maxWidthHeight / actualWidth)
            maxHeight = (actualHeight * per) / 100.0
        }else{
            maxHeight = maxWidthHeight
            let per = (100.0 * maxWidthHeight / actualHeight)
            maxWidth = (actualWidth * per) / 100.0
        }

        let hasAlpha = true
        let scale: CGFloat = 0.0

        UIGraphicsBeginImageContextWithOptions(CGSize(width: maxWidth, height: maxHeight), !hasAlpha, scale)
        self.draw(in: CGRect(origin: .zero, size: CGSize(width: maxWidth, height: maxHeight)))

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        return scaledImage
    }

}
Misspeak answered 18/5, 2017 at 9:8 Comment(0)
P
-1

This question is from several years ago but comes up as I was trying to resize an image. There are apparently new ways that are much easier in SWIFTUI (not UIKit). This works for me:

Image("yourImage").resizable()
                        .aspectRatio(contentMode: .fit)
Plica answered 16/9, 2021 at 16:59 Comment(1)
You have to mention that this's a SwiftUI Code, not UIKitHassett

© 2022 - 2024 — McMap. All rights reserved.