Skip to content

Instantly share code, notes, and snippets.

@christophercotton
Created July 16, 2010 17:00
Show Gist options
  • Save christophercotton/478626 to your computer and use it in GitHub Desktop.
Save christophercotton/478626 to your computer and use it in GitHub Desktop.
Using http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/ but with additions for iPhone 4 hires scale images. Also includes fix for 24bit non alpha images.
// Returns a copy of the image that has been transformed using the given affine transform and scaled to the new size
// The new image's orientation will be UIImageOrientationUp, regardless of the current image's orientation
// If the new size is not integral, it will be rounded up
- (UIImage *)resizedImage:(CGSize)newSize
transform:(CGAffineTransform)transform
drawTransposed:(BOOL)transpose
interpolationQuality:(CGInterpolationQuality)quality {
// COTTON - adding in scaling for iPhone 4
BOOL shouldScale = NO;
CGFloat newScale = 1.0;
if ([UIScreen instancesRespondToSelector:@selector(scale)]) {
shouldScale = YES;
newScale = [[UIScreen mainScreen] scale];
newSize = CGSizeMake(newSize.width * newScale, newSize.height * newScale);
}
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGRect transposedRect = CGRectMake(0, 0, newRect.size.height, newRect.size.width);
CGImageRef imageRef = self.CGImage;
// code to deal with Non Alpha images
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
if (CGImageGetAlphaInfo(imageRef) == kCGImageAlphaNone) {
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaNoneSkipLast;
}
// Build a context that's the same dimensions as the new size
CGContextRef bitmap = CGBitmapContextCreate(NULL,
newRect.size.width,
newRect.size.height,
CGImageGetBitsPerComponent(imageRef),
0,
CGImageGetColorSpace(imageRef),
bitmapInfo);
// Rotate and/or flip the image if required by its orientation
CGContextConcatCTM(bitmap, transform);
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(bitmap, quality);
// Draw into the context; this scales the image
CGContextDrawImage(bitmap, transpose ? transposedRect : newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(bitmap);
UIImage *newImage = nil;
// COTTON - adding in scaling for iPhone 4
if (shouldScale) {
newImage = [UIImage imageWithCGImage:newImageRef scale:newScale orientation:UIImageOrientationUp];
} else {
newImage = [UIImage imageWithCGImage:newImageRef];
}
// Clean up
CGContextRelease(bitmap);
CGImageRelease(newImageRef);
return newImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment