Skip to content

Instantly share code, notes, and snippets.

@sburlot
Created September 4, 2009 09:24
Show Gist options
  • Save sburlot/180812 to your computer and use it in GitHub Desktop.
Save sburlot/180812 to your computer and use it in GitHub Desktop.
- (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 = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL,
rotatedRect.size.width,
rotatedRect.size.height,
8,
0,
colorSpace,
kCGImageAlphaPremultipliedFirst);
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;
}
@JanX2
Copy link

JanX2 commented Jan 31, 2011

The code above was a great starting point, but did not work correctly in any of the tests I did. This repo contains a fixed version derived from the above code:
https://github.com/JanX2/CreateRotateWriteCFImage

@mjarvis
Copy link

mjarvis commented Dec 14, 2011

Changing line 18 from "kCGImageAlphaPremultipliedFirst" to "kCGImageAlphaNone", and line 11 from "CGColorSpaceCreateDeviceRGB" to "CGColorSpaceCreateDeviceGray" will allow rotation of a non-alpha image mask, to be used in CGContextClipToMask.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment