ios

您所在的位置:网站首页 originy轴向下 ios

ios

#ios| 来源: 网络整理| 查看: 265

一、简单介绍

首先我们应该知道在UIKit中,y轴是向下的。而在Core Graphics(Quartz) 中 y轴是向上。

所以其实我们使用CGContextDrawImage来绘图的话,默认是在用户空间下绘制出来的,使用的坐标系是以左下角为原点,y轴向上,x轴向右。

二、实战演练

所以我们在进行绘制的时候,写了如下代码

-(void)drawRect:(CGRect)rect { //获取上下文 CGContextRef context = UIGraphicsGetCurrentContext(); //创建image UIImage * image = [UIImage imageNamed:@"05"]; //指定绘制范围 CGRect rect1 = CGRectMake(0, 0, 200.0, 200.0); 绘制到相应的范围当中去 CGContextDrawImage(context, rect1, image.CGImage); }

得到的是这样的图像,也就是说图像是刚好相反的,因为显示在屏幕上面是使用的是设备的坐标,而这样的话正好设备坐标y轴是向下为正的。也就是可以理解成从用户空间转换成了设备空间。

解决方法就是给图形上下文移动坐标系,具体代码如下所示

-(void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); UIImage * image = [UIImage imageNamed:@"05"]; CGRect rect1 = CGRectMake(0, 0, 200.0, 200.0); CGContextTranslateCTM(context, rect1.origin.x, rect.origin.y); CGContextTranslateCTM(context, 0, rect1.size.height); CGContextScaleCTM(context, 1.0, -1.0); CGContextTranslateCTM(context, -rect1.origin.x, -rect1.origin.y); CGContextDrawImage(context, rect1, image.CGImage); } 三、具体分析

那么为什么这样就可以了呢?原因如下。首先先一步步的来解析。

先介绍下用户空间和设备空间的转换,这里为了好画图,也就用箭头来表示图片了。

1、原来的坐标系

2、下面就开始讲坐标的转化,平移

CGContextTranslateCTM(context, rect1.origin.x, rect.origin.y);

3、一样是平移操作CGContextTranslateCTM(context, 0, rect1.size.height);

4、翻转y轴CGContextScaleCTM(context, 1.0, -1.0);

5、再来平移一次CGContextTranslateCTM(context, -rect1.origin.x, -rect1.origin.y);这个时候平移的就是下面那个坐标了,没有平移前这个翻转过的坐标系

平移之后

这样的话我们再转换到设备坐标,得到的还是这样的原始图像了



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3