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

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


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


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;}


If you don't want to change all the origins and sizes, move the center, rotate and change the center to corner again like this:

CGContextTranslateCTM( context, 0.5f * size.width, 0.5f * size.height ) ;CGContextRotateCTM( context, radians( 90 ) ) ;CGContextTranslateCTM( context, -0.5f * size.width, -0.5f * size.height ) ;

Then draw normally like this:

[image drawInRect:CGRectMake(0, 0, size.width, size.height)];


matomo