0
votes

I have this code snippet:

func resizeImageViewToImageSize(_ imageView:UIImageView) {
        let widthRatio = imageView.bounds.size.width / imageView.image!.size.width
        let heightRatio = imageView.bounds.size.height / imageView.image!.size.height
        let scale = min(widthRatio, heightRatio)
        let imageWidth = scale * imageView.image!.size.width
        let imageHeight = scale * imageView.image!.size.height
        print("\(imageWidth) - \(imageHeight)")

        imageView.frame = CGRect(x: 0,
        y: 70,
        width: imageWidth,
        height: imageHeight)
        imageView.center.x = view.center.x
 }

I call it in viewDidLoad() to resize my originalImageView UIImageView:

resizeImageViewToImageSize(originalImageView)

And it successfully resizes my UIImageView, but in case I take a picture from Camera (on iPhone7+, for instance), my imageWidth and imageHeight are: 226.4 - 283.0, which make my UIImageView very small in the center of the screen, as shown below:

enter image description here

What I would like to do is to have my originalImageViewto be larger in width and keep its scale ratio accordingly, like the mockup below, is that possible?

enter image description here

1

1 Answers

2
votes

I think the problem arises when the value of imageView.image!.size.width is larger than imageView.bounds.size.width or for the height values.

This will result in widthRatio or heightRatio to a value less than 1.

And when your scale is < 1, and multiplied to your imageWidth and imageHeight, you'll end up with a smaller UIImageView than the original.

I'm guessing that the resolution of the image taken from a camera as "clear" as an iPhone7 will be high.

You'll have to check which value is higher imageView.bounds.width or imageView.image!.size.width, and then get the reciprocal depending on the condition.

 func resizeImageViewToImageSize(_ imageView:UIImageView) {


    let maxWidth = view.frame.size.width
    let maxHeight = view.frame.size.height

        var widthRatio = imageView.bounds.size.width / imageView.image!.size.width

        if widthRatio < 1 {
            widthRatio = 1 / widthRatio
        }

        let heightRatio = imageView.bounds.size.height / imageView.image!.size.height

        if heightRatio < 1 {
            heightRatio = 1 / widthRatio
        }

        let scale = min(widthRatio, heightRatio)

        let maxWidthRatio = maxWidth / imageView.bounds.size.width
        let maxHeightRatio = maxHeight / imageView.bounds.size.height
        let maxScale = min(maxWidthRatio, maxHeightRatio)

        let properScale = min(scale, maxScale)

        let imageWidth = properScale * imageView.image!.size.width
        let imageHeight = properScale * imageView.image!.size.height
        print("\(imageWidth) - \(imageHeight)")

        imageView.frame = CGRect(x: 0,
        y: 70,
        width: imageWidth,
        height: imageHeight)
        imageView.center.x = view.center.x
 }