Skip to content

Instantly share code, notes, and snippets.

@ianlevesque
Created June 25, 2010 00:30
Show Gist options
  • Save ianlevesque/452211 to your computer and use it in GitHub Desktop.
Save ianlevesque/452211 to your computer and use it in GitHub Desktop.
@implementation UIImage(Utilities)
-(UIImage *)scaledToSize:(CGSize)size {
// if we're already that size, just return us
if(fabs([self size].width - size.width) < 0.001 && fabs([self size].height - size.height) < 0.001) {
return [[self retain] autorelease]; // we need to do this so that we could release the "original" before retaining the resized "copy"
}
int pixelsWide = size.width + 0.5;
int pixelsHigh = size.height + 0.5;
int bitmapBytesPerRow = (pixelsWide * 4);
int bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
void *bitmapData = malloc(bitmapByteCount);
assert(bitmapData);
CGContextRef context = CGBitmapContextCreate(bitmapData,
pixelsWide,
pixelsHigh,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
assert(context);
CGColorSpaceRelease(colorSpace);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextDrawImage(context, CGRectMake(0, 0, pixelsWide, pixelsHigh), [self CGImage]);
CGImageRef image = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *uiImage = [[[UIImage alloc] initWithCGImage:image] autorelease];
CGImageRelease(image);
free(bitmapData);
return uiImage;
// buggy building on 4.0 targeting 3.1.3...
// assert([NSThread isMainThread]);
// UIGraphicsBeginImageContext(size);
// CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationHigh);
// [self drawInRect:CGRectMake(-10,-10,size.width+20,size.height+20)]; // kludge to ensure we always fill the canvas
// [self drawInRect:CGRectMake(0,0,size.width,size.height)]; // draw it properly
// UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
// return newImage;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment