Resize UIImage with aspect ratio?

I use this code to resize an image on an iPhone:

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

Works great if the aspect ratio of the image matches the image format with the new resized. I would like to change this so that it maintains the correct aspect ratio and simply places the black background anywhere where the image does not appear. Thus, I still get a 320x480 image, but with black top and bottom or sides depending on the size of the original image.

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

+32
ios iphone core-graphics uiimage
Nov 09 '09 at 19:13
source share
1 answer

Once you have set the screen rectangle, do something like the following to decide what to choose to draw the image:

 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 do not want to enlarge images smaller than screenRect, make sure that factor greater than or equal to one (for example, factor = fmax(factor, 1) ).

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

+52
Nov 09 '09 at 19:29
source share



All Articles