Created
November 15, 2014 17:52
-
-
Save brandonscript/a2ab3a8fbd8cfefa0d23 to your computer and use it in GitHub Desktop.
UIImage image rotated by degrees
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
// Requires macros: | |
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI)) | |
#define DEGREES_TO_RADIANS(angle) (angle / 180.0 * M_PI) | |
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees | |
{ | |
// calculate the size of the rotated view's containing box for our drawing space | |
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.size.width, self.size.height)]; | |
CGAffineTransform t = CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees)); | |
rotatedViewBox.transform = t; | |
CGSize rotatedSize = rotatedViewBox.frame.size; | |
// Create the bitmap context | |
UIGraphicsBeginImageContext(rotatedSize); | |
CGContextRef bitmap = UIGraphicsGetCurrentContext(); | |
// Move the origin to the middle of the image so we will rotate and scale around the center. | |
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2); | |
// // Rotate the image context | |
CGContextRotateCTM(bitmap, DEGREES_TO_RADIANS(degrees)); | |
// Now, draw the rotated/scaled image into the context | |
CGContextScaleCTM(bitmap, 1.0, -1.0); | |
CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]); | |
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return newImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment