IOS 绘制图片上下颠倒
在iOS的不同图像处理框架(framework)中使用着不同的坐标系 :
UIKit - x轴向右,y轴向下
Core Graphics(Quartz) - x轴向右,y轴向上
OpenGL ES - x轴向右,y轴向上
UIKit是iPhone SDK的Cocoa Touch层的核心framework,是iPhone应用程序图形界面和事件驱动的基础,坐标系是y轴向下的;
Core Graphics(Quartz)一个基于2D的图形绘制引擎,它的坐标系则是y轴向上的;
OpenGL ES是iPhone SDK的2D和3D绘制引擎,它使用左手坐标系,它的坐标系也是y轴向上的,如果不考虑z轴,在二维下它的坐标系和Quartz是一样的。
通过CGContextDrawImage绘制图片到一个context中时,如果传入的是UIImage的CGImageRef,因为UIKit和Core Graphics坐标系y轴相反,所以图片绘制将会上下颠倒。解决方法:
解决方法一:在绘制到context前通过矩阵垂直翻转坐标系
-
UIImage* uiImage = [UIImage imageNamed:@"test.png"];
-
CGContextTranslateCTM(context, 0, height);
-
CGContextScaleCTM(context, 1.0, -1.0);
-
CGContextDrawImage(context, CGRectMake(0, 0, width, height), uiImage.CGImage);
解决方法二:使用UIImage的drawInRect函数,该函数内部能自动处理图片的正确方向
UIImage* uiImage = [UIImage imageNamed:@"test.png"];
-
UIGraphicsPushContext( context );
-
[uiImage drawInRect:CGRectMake(0, 0, width, height)];
-
UIGraphicsPopContext();