Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 980
dhrm Avatar asked Jan 02 '12 14:01

dhrm


People also ask

How do I resize an image in Objective C?

This is how to use : UIImage *ResizedImage = Resize_Image([UIImage imageNamed:@"image. png"], 64, 14.4);

How do I find the aspect ratio in Swift?

To determine the aspect ratio of a screen: Measure the width and height of the screen. Divide the width by the height.

What is UIImage?

An object that manages image data in your app.


2 Answers

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
}
like image 76
Michał Zygar Avatar answered Sep 27 '22 20:09

Michał Zygar


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;
}
like image 31
Steven Stefanik Avatar answered Sep 27 '22 21:09

Steven Stefanik