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

前端 未结 5 1183
一生所求
一生所求 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:48

    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

提交回复
热议问题