Search code examples
iosswiftuiimageviewuiimage

Can I resize just the image of an imageView?


I have this code:

override func viewDidLoad() {
        super.viewDidLoad()
        let imageView = UIImageView()
        view.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.borderWidth = 5
        imageView.layer.borderColor = UIColor.green.cgColor
        NSLayoutConstraint.activate([
            imageView.heightAnchor.constraint(equalToConstant: 200),
            imageView.widthAnchor.constraint(equalToConstant: 200),
            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0),
            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0),
        ])
        let image = UIImage(named: "3")
        //let image = UIImage(named: "3")?.resizeImageWith(newSize: CGSize(width: 5,height: 5))
        imageView.image = image
    }

That looks like this: enter image description here

Im trying to resize just the image ( so like from the green border there is a margin) with this extension:

func resizeImageWith(newSize: CGSize) -> UIImage {
        let horizontalRatio = newSize.width / size.width
        let verticalRatio = newSize.height / size.height
        let ratio = min(horizontalRatio, verticalRatio)
        let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
        draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }

But when I use that like this:

let image = UIImage(named: "3")?.resizeImageWith(newSize: CGSize(width: 60,height: 60))

I get the following result: enter image description here

And same with this:

let image = UIImage(named: "3")?.resizeImageWith(newSize: CGSize(width: 5,height: 5))

The image just get worst. Is it possible to just resize the image in order to have a margin from the imageView? Thank you! enter image description here


Solution

  • Change the image view content mode to Center:

    imageView.contentMode = .center