Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating an image context (CGContextRotateCTM) causing it to become blank. Why?

#define radians(degrees) (degrees * M_PI/180)  UIImage *rotate(UIImage *image) {   CGSize size = image.size;;    UIGraphicsBeginImageContext(size);   CGContextRef context = UIGraphicsGetCurrentContext();    // If this is commented out, image is returned as it is.   CGContextRotateCTM (context, radians(90));    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];   UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();   UIGraphicsEndImageContext();    return newImage; } 

Could something else be wrong? Out of ideas.

like image 765
Gurpartap Singh Avatar asked May 12 '11 19:05

Gurpartap Singh


2 Answers

The problem is your context is being rotated around (0,0) which is the top left corner. If you rotate 90 degrees around the top left corner, all your drawing will occur out of the bounds of the context. You need a 2-step transform to move the origin of the context to it's middle, and THEN rotate. Also you need to draw your image centered around the moved/rotated origin, like this:

CGContextTranslateCTM( context, 0.5f * size.width, 0.5f * size.height ) ; CGContextRotateCTM( context, radians( 90 ) ) ;  [ image drawInRect:(CGRect){ { -size.width * 0.5f, -size.height * 0.5f }, size } ] ; 

HTH

like image 67
nielsbot Avatar answered Oct 07 '22 00:10

nielsbot


I try followed code, it works, get from http://www.catamount.com/blog/1015/uiimage-extensions-for-cutting-scaling-and-rotating-uiimages/

+ (UIImage *)rotateImage:(UIImage*)src byRadian:(CGFloat)radian {     // calculate the size of the rotated view's containing box for our drawing space     //UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0,0, src.size.width, src.size.height)];     //CGAffineTransform t = CGAffineTransformMakeRotation(radian);     //rotatedViewBox.transform = t;     //CGSize rotatedSize = rotatedViewBox.frame.size;     CGRect rect = CGRectApplyAffineTransform(CGRectMake(0,0, src.size.width, src.size.height), CGAffineTransformMakeRotation(radian));     CGSize rotatedSize = rect.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, radian);      // Now, draw the rotated/scaled image into the context     CGContextScaleCTM(bitmap, 1.0, -1.0);     CGContextDrawImage(bitmap, CGRectMake(-src.size.width / 2, -src.size.height / 2, src.size.width, src.size.height), [src CGImage]);      UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();     UIGraphicsEndImageContext();     return newImage; } 
like image 27
lbsweek Avatar answered Oct 06 '22 23:10

lbsweek