0

I'm just trying to rotate a UIImage around its center using the following piece of code:

- (UIImage *) rotateImage: (UIImage *)image angle:(CGFloat)angleInRadian
    {
        float newSide = MAX([image size].width, [image size].height);
        CGSize size =  CGSizeMake(newSide, newSide);
        UIGraphicsBeginImageContext(size);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(ctx, newSide/2, newSide/2);
        CGContextRotateCTM(ctx, angleInRadian);
        CGContextDrawImage(UIGraphicsGetCurrentContext(),CGRectMake(-[image size].width/2,-[image size].height/2,size.width, size.height),image.CGImage);
        //CGContextTranslateCTM(ctx, [image size].width/2, [image size].height/2);
        
        UIImage *i = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return i;
    }

Here is a sample of the results I got:

Input image:

enter image description here

Result Image for angle = 0 radians :

enter image description here

The result image is flipped but I'm not sure why? Any idea about what I'm doing wrong?

Thanks in advance.

Community
  • 1
  • 1
Maystro
  • 2,907
  • 8
  • 36
  • 71
  • 1
    It is possible the UIImage you get is already flipped. If so this property is lost once you call the CGImage property on it. Anyway all of this can be avoided and done extremely easily by simply putting the image onto the image view, do the transformations on the view and create a screenshot. – Matic Oblak Jan 12 '15 at 11:27
  • I already did it and it did not work – Maystro Jan 12 '15 at 12:30

2 Answers2

0

Seems a bit overkill for what you want. Have you tried looking at CGAffineTransformRotate:

 CGAffineTransformRotate(rotation.view.transform, angle);
pidge
  • 20
  • 3
  • You can't transform the image itself that's why I'm using the context. This can be applied on UIImageView for instance. – Maystro Jan 12 '15 at 12:27
0

Add this line after CGContextRotateCTM

CGContextScaleCTM(ctx, 1.0, -1.0);

UIKit coordinate system is upside down to Quartz coordinate system. See here for more details

https://developer.apple.com/library/ios/qa/qa1708/_index.html

Also check image orientation.

Jun
  • 3,422
  • 3
  • 28
  • 58