简体   繁体   中英

UIImageView: Change size to image size?

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?

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
}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM