15
votes

I've an UIImageView with content mode Aspect Fit of size 220x155. I'm dynamically inserting different images in different resolutions, but all larger than the size of the UIImageView. As the content mode is set to Aspect Fit, the image is scaled with respect to the ratio to fit the UIImageView.

My problem is, that if for instance the image inside the UIImageView is scaled to 220x100, I would like the UIImageView to shrink from a height of 155 to 100 too to avoid space between my elements.

How can I do this?

4
i have a same problem the image is set at center but get space in upper and lower side. how can i resolve it? please help meHiren

4 Answers

28
votes

If I got you right, it would be something like this: get image size by:

UIImage * img = [UIImage imageNamed:@"someImage.png"];
CGSize imgSize = img.size;

calculate scale ratio on width

float ratio=yourImageView.frame.size.width/imgSize.width;

check scaled height (using same ratio to keep aspect)

float scaledHeight=imgSize.height*ratio;
if(scaledHeight < yourImageView.frame.size.height)
{
   //update height of your imageView frame with scaledHeight
}
20
votes

Based on Michael's answer, here's a complete method

+ (CGSize)makeSize:(CGSize)originalSize fitInSize:(CGSize)boxSize
{
    float widthScale = 0;
    float heightScale = 0;

    widthScale = boxSize.width/originalSize.width;
    heightScale = boxSize.height/originalSize.height;

    float scale = MIN(widthScale, heightScale);

    CGSize newSize = CGSizeMake(originalSize.width * scale, originalSize.height * scale);

    return newSize;
}
3
votes

Edit for Steven Stefanik's answer: This method breaks when originalSize is {0, 0}. Maybe consider these changes

-(CGSize)makeSize:(CGSize)originalSize fitInSize:(CGSize)boxSize
{
    if (originalSize.height == 0) {
        originalSize.height = boxSize.height;
    }
    if (originalSize.width == 0) {
        originalSize.width = boxSize.width;
    }

    float widthScale = 0;
    float heightScale = 0;

    widthScale = boxSize.width/originalSize.width;
    heightScale = boxSize.height/originalSize.height;

    float scale = MIN(widthScale, heightScale);

    CGSize newSize = CGSizeMake(originalSize.width * scale, originalSize.height * scale);

    return newSize;
}
0
votes

Last edit:

It seems I misunderstood the question.

To get the actual size you could try:

CGSize imageSize = img.size;
CGSize viewSize = imageView.frame.size;
CGSize actualSize;

if (imageSize.width > imageSize.height) {
    actualSize.width = imageSize.width > viewSize.width ? viewSize.width : imageSize.width;

    actualSize.height = imageSize.height * actualSize.width / imageSize.width;
}
else {
    actualSize.height = imageSize.height > viewSize.height ? viewSize.height : imageSize.height;

    actualSize.width = imageSize.width * actualSize.height / imageSize.height;
}