Created
August 24, 2013 23:21
-
-
Save indyfromoz/6330970 to your computer and use it in GitHub Desktop.
Resize UIImageView based on the size of the screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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