1
votes

What is the best way to manually reproduce

contentMode = UIViewContentModeScaleAspectFit;

without using it?

I need to scale a UIImageView (inside a scroll view) to fit the aspect ratio. I need to know the new size of the image to draw overlays over it.

1

1 Answers

3
votes

Recently, I needed to find the frame of the image inside an ImageView, to add touchable views over that image, this is how I did it:

-(void)calculateScaleAndContainerFrame{
    if(!imageView || !image) return;

    CGSize imageSize = image.size;
    CGSize imageViewSize = imageView.frame.size;

    float imageRatio = imageSize.width / imageSize.height;
    float viewRatio = imageViewSize.width / imageViewSize.height;

    if(imageRatio > viewRatio){
        scale = imageSize.width / imageViewSize.width;
    }else{
        scale = imageSize.height / imageViewSize.height;
    }

    CGRect frame = CGRectZero;

    frame.size = CGSizeMake(roundf(imageSize.width / scale), roundf(imageSize.height / scale));
    frame.origin = CGPointMake((imageViewSize.width - frame.size.width) / 2.0, (imageViewSize.height - frame.size.height) / 2.0);

    [container setFrame:frame];
}

I'm pretty sure you can use it as a guide, replacing the imageViewSize with the content size of your scroll view (or the view you want to put your image in).

Note 1: In my case, I needed to center the view vertically, if you don't, just set the y to 0 on the line where I set the frame origin. Same for x if you don't want to center the image horizontally.

Note 2: This is NOT, by any means, a code you can just plug in into your project and work, you'll probably have to read it, understand it, and then apply the method to your own project. I don't have time right now to modify it to your needs.

Note 3: With that code I managed to get a view perfectly over the image inside a image view that used that content mode, so it works.