Skip to content

Instantly share code, notes, and snippets.

@indyfromoz
Created August 24, 2013 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indyfromoz/6330970 to your computer and use it in GitHub Desktop.
Save indyfromoz/6330970 to your computer and use it in GitHub Desktop.
Resize UIImageView based on the size of the screen
// From http://stackoverflow.com/questions/12648129/uiimageview-programmilly-manage-for-iphone5-and-iphone4/12774544#12774544
[self resizeImageView:self.backgroundImageView intoFrame:self.view.frame];
- (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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment