Skip to content

Instantly share code, notes, and snippets.

@Kjuly
Created February 13, 2014 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kjuly/8979119 to your computer and use it in GitHub Desktop.
Save Kjuly/8979119 to your computer and use it in GitHub Desktop.
Rotate UIImage instance (90 degree as an e.g. here).
UIImage * image = ...
// Redraw image with rotation
CGSize originalSize = image.size;
CGSize finalSize = CGSizeMake(originalSize.height, originalSize.width);
UIGraphicsBeginImageContext(finalSize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformTranslate(transform, originalSize.width * .5f, originalSize.height * .5f);
transform = CGAffineTransformRotate(transform, 90.f * M_PI / 180.f);
// -1.f here means fliping matrix vertical
transform = CGAffineTransformScale(transform, 1.f, -1.f);
CGContextConcatCTM(context, transform);
CGContextTranslateCTM(context, -finalSize.width * .5f, -finalSize.height * .5f);
CGContextDrawImage(context, (CGRect){CGPointZero, originalSize}, image.CGImage);
UIImage * rotatedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return rotatedImage;
@Kjuly
Copy link
Author

Kjuly commented Feb 13, 2014

Note, don't forget this step

transform = CGAffineTransformScale(transform, 1.f, -1.f);

otherwise, the final image will be up side down.

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