I had the same problem and below I did what I did to make it work for me.
I have images used in several applications that need to be changed for a new 4-inch display. I wrote the code below to automatically resize images as needed without any special features at the height of the presentation. This code assumes that the height of a given image has been set in the NIB as the full height of a given frame, for example, this is a background image that fills the entire view. In NIB, the UIImageView should not stretch, which will stretch the image for you and distort the image, since only the height changes and the width remains the same. What you need to do is adjust the height and width to the same delta, and then shift the image to the left of the same delta to center it again. This shrinks a bit on both sides, while it expands to the full height of the given frame.
I call it that way ...
[self resizeImageView:self.backgroundImageView intoFrame:self.view.frame];
I do this in viewDidLoad usually if the image is set to NIB. But I also have images that are loaded at runtime and displayed in this way. These images are cached using EGOCache, so I have to call the resize method either after installing the cached image in UIImageView, or after loading the image and installing in UIImageView.
The code below doesn't really care what the height of the display is. In fact, he could work with any screen size, possibly for processing images with resizing for rotation, assuming that he assumes every time the change in height is greater than the original height. To maintain large widths, this code will need to be adjusted to respond to this scenario.
- (void)resizeImageView:(UIImageView *)imageView intoFrame:(CGRect)frame { // resizing is not needed if the height is already the same if (frame.size.height == imageView.frame.size.height) { return; } CGFloat delta = frame.size.height / imageView.frame.size.height; CGFloat newWidth = imageView.frame.size.width * delta; CGFloat newHeight = imageView.frame.size.height * delta; CGSize newSize = CGSizeMake(newWidth, newHeight); CGFloat newX = (imageView.frame.size.width - newWidth) / 2; // recenter image with broader width CGRect imageViewFrame = imageView.frame; imageViewFrame.size.width = newWidth; imageViewFrame.size.height = newHeight; imageViewFrame.origin.x = newX; imageView.frame = imageViewFrame; // now resize the image assert(imageView.image != nil); imageView.image = [self imageWithImage:imageView.image scaledToSize:newSize]; } - (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize { UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0); [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
Brennan Oct 08 '12 at 2:11 2012-10-08 02:11
source share