I am new to developing code in iPhone, and I want to search some code to resize my UIImage to a specified size but keep the ratio. The specified size is something like a frame that the image can’t come cross the boundary, within that boundary the image should scale to fit the frame and keep the ratio, the code I am currently using can do resize but can’t keep the ratio, just paste it here to see if I can do some trivial modifications so that it can make it possible.
- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = image.CGImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
CGContextConcatCTM(context, flipVertical);
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
return newImage;
}
well, you could resize the image a bit simpler:
Then you need to calculate a new size that maintenance the aspect ratio.
e.g. to get a image Half the size you would provide a size created like this: