8

I have been using the code in this sample to assist and this works well. http://www.platinumball.net/blog/2009/03/30/iphone-uiimage-rotation-and-mirroring/

I cannot workout how to rotate by a custom amount of degrees between 0 & 360....

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Lee Armstrong
  • 11,420
  • 15
  • 74
  • 122

1 Answers1

14

You'll want to do pretty much the same stuff as in that post does in rotate:

CGSize size = sizeOfImage;
UIGraphicsBeginImageContext(size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextRotateCTM(ctx, angleInRadians);
CGContextDrawImage(ctx, (CGRect){{}, size}, image);

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;

You might need to also translate the CTM in addition to rotating to compensate for the center of rotation. If you want to not crop the edges of the image when rotating, you should increase the size with some basic trig.

Andrew Pouliot
  • 5,423
  • 1
  • 30
  • 34
  • 1
    `ctx` is just the graphics context. I updated the source to indicate that. – Andrew Pouliot Jun 13 '11 at 21:19
  • @AndrewPouliot:That is really great.But how do i set the center of rotation for the image? – Shantanu Jul 31 '12 at 07:50
  • @Shantanu: CGContextTranslateCTM(ctx, -centerOfRotation.x, -centerOfRotation.y), rotate, then CGContextTranslateCTM(ctx, centerOfRotation.x, centerOfRotation.y); – Andrew Pouliot Aug 01 '12 at 08:10
  • Why do you store a reference to the current graphics context with `UIGraphicsGetCurrentContext()`, and then run `UIGraphicsGetCurrentContext()` again two lines later? –  Sep 11 '12 at 09:12
  • UIGraphicsGetImageFromCurrentImageContext() returns nil and thus the image is nil. How would you solve this problem? – coolcool1994 Apr 07 '14 at 23:38