Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize UIImage with aspect ratio?

I'm using this code to resize an image on the iPhone:

CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:kCGBlendModePlusDarker alpha:1]; UIImage *tmpValue = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); 

Which is working great, as long as the aspect ratio of the image matches that of the new resized image. I'd like to modify this so that it keeps the correct aspect ratio and just puts a black background anywhere the image doesn't show up. So I would still end up with a 320x480 image but with black on the top and bottom or sides, depending on the original image size.

Is there an easy way to do this similar to what I'm doing? Thanks!

like image 746
Cory Imdieke Avatar asked Nov 09 '09 19:11

Cory Imdieke


People also ask

How do I find my aspect ratio in UIImage?

size. height * scaleFactor let newWidth = oldWidth * scaleFactor UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight)) sourceImage. draw(in: CGRect(x:0, y:0, width:newWidth, height:newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! }

What is a 2 3 aspect ratio?

As another example, a portrait-style image might have a ratio of 2:3. With this aspect ratio, the height is 1.5 times longer than the width. So the image could be 500px × 750px, 1500px × 2250px, etc.

How do I resize an image in Xcode?

Assuming that you are referring to the layout in storyboard/IB. To get the native size of the image just select the image and press Command + = on the keyboard. the to re-size it proportionally select the corner and hold down the shift key when you re-size it.


1 Answers

After you set your screen rect, do something like the following to decide what rect to draw the image in:

float hfactor = value.bounds.size.width / screenRect.size.width; float vfactor = value.bounds.size.height / screenRect.size.height;  float factor = fmax(hfactor, vfactor);  // Divide the size by the greater of the vertical or horizontal shrinkage factor float newWidth = value.bounds.size.width / factor; float newHeight = value.bounds.size.height / factor;  // Then figure out if you need to offset it to center vertically or horizontally float leftOffset = (screenRect.size.width - newWidth) / 2; float topOffset = (screenRect.size.height - newHeight) / 2;  CGRect newRect = CGRectMake(leftOffset, topOffset, newWidth, newHeight); 

If you don't want to enlarge images smaller than the screenRect, make sure factor is greater than or equal to one (e.g. factor = fmax(factor, 1)).

To get the black background, you would probably just want to set the context color to black and call fillRect before drawing the image.

like image 151
Frank Schmitt Avatar answered Oct 07 '22 23:10

Frank Schmitt