Skip to content

Instantly share code, notes, and snippets.

@paolonl
Last active July 3, 2018 14:16
Show Gist options
  • Save paolonl/6231410 to your computer and use it in GitHub Desktop.
Save paolonl/6231410 to your computer and use it in GitHub Desktop.
Rotate UIImage/CGImageRef
- (UIImage *)rotateImage:(UIImage *)image ofAngle:(CGFloat)degrees {
CGImageRef imgRef = image.CGImage;
CGFloat angleInRadians = degrees * (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,
CGImageGetBitsPerComponent(imgRef),
0,
colorSpace,
kCGImageAlphaPremultipliedFirst);
CGContextSetAllowsAntialiasing(bmContext, NO);
CGContextSetInterpolationQuality(bmContext, kCGInterpolationNone);
CGColorSpaceRelease(colorSpace);
CGContextTranslateCTM(bmContext,
+(rotatedRect.size.width/2),
+(rotatedRect.size.height/2));
CGContextRotateCTM(bmContext, angleInRadians);
CGContextDrawImage(bmContext, CGRectMake(-width/2, -height/2, width, height),
imgRef);
CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext);
CFRelease(bmContext);
UIImage *finalImage = [UIImage imageWithCGImage:rotatedImage];
CFRelease(rotatedImage);
return finalImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment