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

前端 未结 5 1191
一生所求
一生所求 2020-12-05 00:23
#define radians(degrees) (degrees * M_PI/180)

UIImage *rotate(UIImage *image) {
  CGSize size = image.size;;

  UIGraphicsBeginImageContext(size);
  CGContextRef co         


        
5条回答
  •  醉话见心
    2020-12-05 00:38

    Expanding on Nielsbot's answer, I created the following snippet. Note that this should preferably be made a function rather than a code snippet, to prevent 'copy/paste programming'. I didn't get to that yet, so feel free to adapt it.

    Code snippet:

    // 
    UIImage* imageToDrawRotated = <#image#>;
    float rotationAngle = <#angle#>;
    CGRect drawFrame = CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>);
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), floor(drawFrame.origin.x + drawFrame.size.width/2), floor(drawFrame.origin.y + drawFrame.size.height/2));
    CGContextRotateCTM(UIGraphicsGetCurrentContext(), rotationAngle);
    [imageToDrawRotated drawInRect:CGRectMake(-floor(drawFrame.size.width/2), -floor(drawFrame.size.height/2), drawFrame.size.width, drawFrame.size.height)];
    CGContextRotateCTM(UIGraphicsGetCurrentContext(), -rotationAngle);
    CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -floor(drawFrame.origin.x + drawFrame.size.width/2), -floor(drawFrame.origin.y + drawFrame.size.height/2));
    // 
    

    Also, I welcome a better way to reset the CGContext to its previous state.

提交回复
热议问题