Marti Serra Vivancos
Marti Serra Vivancos

Reputation: 1179

Issue rotating UIImage

I'm developing an iOS 6 app for iPad. I've developed some code which rotates a UIImage. It works great with square images, but when the images aren't square they get cropped, so you only see a part of the image (a square).

My code:

UIGraphicsBeginImageContext(image.size);

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextTranslateCTM( context, 0.5f * image.size.width, 0.5f * image.size.height ) ;
CGContextRotateCTM( context, -1.5707963267949) ;

[image drawInRect:(CGRect){ { -imatgetemporal.size.width * 0.5f, -image.size.height * 0.5f }, image.size }];

UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();

I think the problem is in the 0.5f, but I don't know how to solve it. What can I do?

Upvotes: 4

Views: 332

Answers (1)

Aaron Golden
Aaron Golden

Reputation: 7102

You need to make your graphics context big enough for the rotated image. You're using image.size, but should be using a the rotated size as the argument to UIGraphicsBeginImageContext. Additionally, your argument to drawInRect is incorrect. You need to offset the (rotated) origin x, which determines the y origin of the final image, in the following way: "Up" by half the original height (which puts the final image entirely off the top of the drawing context) then "down" by the full original width, which is the final image height.

const CGSize imageSize = image.size;
UIGraphicsBeginImageContext(CGSizeMake(imageSize.height, imageSize.width));

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.5f * imageSize.width, 0.5f * imageSize.height ) ;
CGContextRotateCTM(context, -1.5707963267949) ;
[image drawInRect:(CGRect){ { imageSize.height * 0.5 - imageSize.width, -imageSize.width * 0.5f }, imageSize }];

UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();

Upvotes: 1

Related Questions