How do set a width and height of an Image in Swift How do set a width and height of an Image in Swift ios ios

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


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 wantvar image = UIImage(named: "myImage.png");imageView.image = image;self.view.addSubview(imageView);


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)


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!    }}