Quartz 2D的坐标系和UIKit的坐标系对比以及相互转换

来源:互联网 发布:c语言游戏开发教程 编辑:程序博客网 时间:2024/05/29 14:29

Quartz 2D和UIKit的坐标系是不同的,这个也就可以理解为什么用Quartz 2D画和UIKit的倒过来的。

先看看下图:

屏幕快照 2013-04-23 上午10.19.29

左边的坐标系是Quartz 2D的坐标系,原点在左下角。右边是UIKit的坐标系,原点在右上角。我们代码来直观说明一下两者的关系:

1、首先用常规的方式在屏幕上把icon图片打印出来。看看原始的icon图片是什么样子的。

   UIImage *image =[UIImage imageNamed:@"icon@2x.png"];    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10 , 57, 57)];    imageView.clipsToBounds = NO;    [imageView  setImage:image];    [self.view addSubview:imageView];

运行看结果,结果如下(完全意料之中的结果):

屏幕快照 2013-04-23 上午10.26.16

 

2、接下来,我们看看Quartz 2D的表现是什么样的。

UIImage *image =[UIImage imageNamed:@"icon@2x.png"];UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10 , 57, 57)];imageView.clipsToBounds = NO;[self.view addSubview:imageView];UIGraphicsBeginImageContext(CGSizeMake(image.size.width, image.size.height));//新建一个Quartz ContextCGContextRef context = UIGraphicsGetCurrentContext();CGContextDrawImage(context,CGRectMake(0, 0, image.size.width, image.size.height) , [image CGImage]); //把图片打印在Quartz Context上面UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();//从Quartz Context上面获取图片的结果UIGraphicsEndImageContext();[imageView setImage:resultImage];//把从Quartz Context上面获取到的图片显示到UIKit的Context里面来

结果如下图所示:

屏幕快照 2013-04-23 上午10.28.51

我们可以得出的结果就是,Quartz 2D和UIKit的坐标系是在Y轴方向的镜像关系的。

接下来,就是一个关键问题了,如何把Quartz 2D中画的图正常的显示到UIKit体系中呢?

答案就是对Quartz 2D的坐标系进行转换:

UIGraphicsBeginImageContext(CGSizeMake(image.size.width, image.size.height));CGContextRef context = UIGraphicsGetCurrentContext();CGContextRotateCTM(context, M_PI); //先旋转180度,是按照原先顺时针方向旋转的。这个时候会发现位置偏移了CGContextScaleCTM(context, -1, 1); //再水平旋转一下CGContextTranslateCTM(context,0, -image.size.height);//再把偏移掉的位置调整回来CGContextDrawImage(context,CGRectMake(0, 0, image.size.width, image.size.height) , [image CGImage]); UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();

先运行看看结果:

屏幕快照 2013-04-23 上午10.26.16

结果正常了,要理解上面代码的意图关键要理解这三句代码:

CGContextRotateCTM(context, M_PI); //先旋转180度,是按照原先顺时针方向旋转的。这个时候会发现位置偏移了CGContextScaleCTM(context, -1, 1); //再水平旋转一下CGContextTranslateCTM(context,0, -image.size.height);//再把偏移掉的位置调整回来

其中,旋转、翻转然后偏移。要理解这三句代码,关键要清楚CTM的含义:current transformation matrix(当前变换矩阵),一个矩阵用来变换context的坐标系的。关键是变换的context的坐标系,而不是context里面的内容。和UIView的transform是不一样的概念。

用下面的图片来说明这个变化过程:

屏幕快照 2013-04-23 上午11.11.15

通过这个几个步骤,把Quartz转成UIKit一致的坐标系了。

0 0
原创粉丝点击