旋转图像上下文(CGContextRotateCTM)使其变为空白。为什么? [英] Rotating an image context (CGContextRotateCTM) causing it to become blank. Why?

查看:1431
本文介绍了旋转图像上下文(CGContextRotateCTM)使其变为空白。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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.

推荐答案

问题是您的上下文正在左右角(0,0)左右旋转。如果围绕左上角旋转90度,则所有绘图都将出现在上下文的边界之外。你需要一个两步变换来将上下文的原点移动到它的中间,然后旋转。此外,您需要以移动/旋转原点为中心绘制图像,如下所示:

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

这篇关于旋转图像上下文(CGContextRotateCTM)使其变为空白。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆