Forked from sburlot/Arbitrary rotation of a CGImage
Created
December 14, 2011 22:20
-
-
Save mjarvis/1478834 to your computer and use it in GitHub Desktop.
Grayscale for CGContextClipToMask
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
- (CGImageRef)CGImageRotatedByAngle:(CGImageRef)imgRef angle:(CGFloat)angle | |
{ | |
CGFloat angleInRadians = angle * (M_PI / 180); | |
CGFloat width = CGImageGetWidth(imgRef); | |
CGFloat height = CGImageGetHeight(imgRef); | |
CGRect imgRect = CGRectMake(0, 0, width, height); | |
CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians); | |
CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform); | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); | |
CGContextRef bmContext = CGBitmapContextCreate(NULL, | |
rotatedRect.size.width, | |
rotatedRect.size.height, | |
8, | |
0, | |
colorSpace, | |
kCGImageAlphaNone); | |
CGContextSetAllowsAntialiasing(bmContext, FALSE); | |
CGContextSetInterpolationQuality(bmContext, kCGInterpolationNone); | |
CGColorSpaceRelease(colorSpace); | |
CGContextTranslateCTM(bmContext, | |
+(rotatedRect.size.width/2), | |
+(rotatedRect.size.height/2)); | |
CGContextRotateCTM(bmContext, angleInRadians); | |
CGContextTranslateCTM(bmContext, | |
-(rotatedRect.size.width/2), | |
-(rotatedRect.size.height/2)); | |
CGContextDrawImage(bmContext, CGRectMake(0, 0, | |
rotatedRect.size.width, | |
rotatedRect.size.height), | |
imgRef); | |
CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext); | |
CFRelease(bmContext); | |
[(id)rotatedImage autorelease]; | |
return rotatedImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment