iOS 各种坐标系对比

来源:互联网 发布:apache url重写规则 编辑:程序博客网 时间:2024/04/28 10:37


  • 使用CGContextDrawImage绘制图片上下颠倒

    首先要说的是,在iOS的不同framework中使用着不同的坐标系:

    • UIKit - y轴向下
    • Core Graphics(Quartz) - y轴向上
    • OpenGL ES - y轴向上

    UIKit是iPhone SDK的Cocoa Touch层的核心framework,是iPhone应用程序图形界面和事件驱动的基础,它和传统的windows桌面一样,坐标系是y轴向下的; Core Graphics(Quartz)一个基于2D的图形绘制引擎,它的坐标系则是y轴向上的;而OpenGL ES是iPhone SDK的2D和3D绘制引擎,它使用左手坐标系,它的坐标系也是y轴向上的,如果不考虑z轴,在二维下它的坐标系和Quartz是一样的。

    现在回到问题,当通过CGContextDrawImage绘制图片到一个context中时,如果传入的是UIImage的CGImageRef,因为UIKit和CG坐标系y轴相反,所以图片绘制将会上下颠倒。解决方法有以下几种,

    解决方法一:在绘制到context前通过矩阵垂直翻转坐标系

    // uiImage是将要绘制的UIImage图片,width和height是它的宽高CGContextTranslateCTM(context, 0, height);CGContextScaleCTM(context, 1.0, -1.0);CGContextDrawImage(context, CGRectMake(0, 0, width, height), uiImage.CGImage);

    解决方法二:使用UIImage的drawInRect函数,该函数内部能自动处理图片的正确方向

    // uiImage是将要绘制的UIImage图片,width和height是它的宽高UIGraphicsPushContext( context );[uiImage drawInRect:CGRectMake(0, 0, width, height)];UIGraphicsPopContext();

    解决方法三:垂直翻转投影矩阵
    这种方法通过设置上下颠倒的投影矩阵,使得原本y轴向上的GL坐标系看起来变成了y轴向下,并且坐标原点从屏幕左下角移到了屏幕左上角。如果你习惯使用y轴向下的坐标系进行二维操作,可以使用这种方法,同时原本颠倒的图片经过再次颠倒后回到了正确的方向:

    // uiImage是将要绘制的UIImage图片,width和height是它的宽高// 图片被颠倒的绘制到contextCGContextDrawImage(context, CGRectMake(0, 0, width, height), uiImage.CGImage);// 设置上下颠倒的投影矩阵(则原来颠倒的图片回到了正确的方向)glMatrixMode(GL_PROJECTION);glLoadIdentity();glOrthof( 0, framebufferWidth, framebufferHeight, 0, -1, 1 );
    iPhone Core Graphics 和 Quartz的关系

    quartz属于core graphic framework的一部分.

    为什么都说quartz的坐标系都在左下角呢?因为那是在mac x os里面,如果在iPhone OS中,坐标系是左上角的.

    Note: If you are using Quartz 2D for an iPhone application, make sure you understand the native coordinate system of iPhone OS. Its origin is located at the upper left. For more details, see “Drawing to a Graphics Context in iPhone OS.

  • 原创粉丝点击