Created
May 31, 2011 20:06
-
-
Save yanks/1001162 to your computer and use it in GitHub Desktop.
This file contains 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
- (UIImage*)upsideDownBunny { | |
__block CGImageRef cgImg; | |
__block CGSize imgSize; | |
__block UIImageOrientation orientation; | |
dispatch_block_t createStartImgBlock = ^(void) { | |
// UIImages should only be accessed from the main thread | |
UIImage *img = [UIImage imageNamed:@"bunny.png"]; | |
imgSize = [img size]; // this size will be pre rotated | |
orientation = [img imageOrientation]; | |
cgImg = CGImageRetain([img CGImage]); // this data is not rotated | |
}; | |
if([NSThread isMainThread]) { | |
createStartImgBlock(); | |
} else { | |
dispatch_sync(dispatch_get_main_queue(), createStartImgBlock); | |
} | |
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); | |
// in iOS4+ you can let the context allocate memory by passing NULL | |
CGContextRef context = CGBitmapContextCreate( NULL, | |
imgSize.width, | |
imgSize.height, | |
8, | |
imgSize.width * 4, | |
colorspace, | |
kCGImageAlphaPremultipliedLast); | |
// rotate so the image respects the original UIImage's orientation | |
switch (orientation) { | |
case UIImageOrientationDown: | |
CGContextTranslateCTM(context, imgSize.width, imgSize.height); | |
CGContextRotateCTM(context, M_PI); | |
break; | |
case UIImageOrientationLeft: | |
CGContextTranslateCTM(context, 0.0, imgSize.height); | |
CGContextRotateCTM(context, 3.0 * M_PI / 2.0); | |
break; | |
case UIImageOrientationRight: | |
CGContextTranslateCTM(context,imgSize.width, 0.0); | |
CGContextRotateCTM(context, M_PI / 2.0); | |
break; | |
default: | |
// there are mirrored modes possible | |
// but they aren't generated by the iPhone's camera | |
break; | |
} | |
// rotate the image upside down | |
CGContextRotateCTM(context, M_PI); | |
CGContextTranslateCTM(context, -imgSize.width, -imgSize.height); | |
CGContextDrawImage( context, CGRectMake(0.0, 0.0, imgSize.width, imgSize.height), cgImg ); | |
// grab the new rotated image | |
CGContextFlush(context); | |
CGImageRef newCgImg = CGBitmapContextCreateImage(context); | |
__block UIImage *newImage; | |
dispatch_block_t createRotatedImgBlock = ^(void) { | |
// UIImages should only be accessed from the main thread | |
newImage = [UIImage imageWithCGImage:newCgImg]; | |
}; | |
if([NSThread isMainThread]) { | |
createRotatedImgBlock(); | |
} else { | |
dispatch_sync(dispatch_get_main_queue(), createRotatedImgBlock); | |
} | |
CGColorSpaceRelease(colorspace); | |
CGImageRelease(newCgImg); | |
CGContextRelease(context); | |
return newImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment