zoukankan      html  css  js  c++  java
  • IOS图像处理(4)坐标变化

    在IOS中进行绘图都是根据点来确定位置,这里就有了坐标系的概念

    在Core Graphics中坐标系的坐标原点在屏幕左下角,沿y轴正方向是向上的,而在UIKit中坐标原点在屏幕左上角,沿y轴正方向向下。

    我们可以通过一个3行3列的变换矩阵对2维坐标系进行任意转换(或者通过更加简便的API),常用的转换包括移动(translate),缩放(scale)以及旋转(rotate)。

    1 移动

    - (void)drawRect:(CGRect)rect
    {
        //获取图像上下文对象
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        
        CGContextTranslateCTM(context, 50, 30);
        UIImage *image = [UIImage imageNamed:@"mario.jpg"];
        [image drawInRect:rect];
    }

     

    2缩放

    - (void)drawRect:(CGRect)rect
    {
        //获取图像上下文对象
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        //X轴与Y轴均为之前的0.5倍
        CGContextScaleCTM(context, 0.5, 0.5);
        UIImage *image = [UIImage imageNamed:@"mario.jpg"];
        [image drawInRect:rect];
    }

    3旋转

    - (void)drawRect:(CGRect)rect
    {
        //获取图像上下文对象
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        //旋转30度(相对于原点(0,0))
        CGContextRotateCTM(context, 30 * M_PI / 180);
        UIImage *image = [UIImage imageNamed:@"mario.jpg"];
        [image drawInRect:rect];
    }

    如果频繁的进行坐标变化,往往会导致开发者分不清当前坐标的状态以及坐标原点的位置,此时可以使用

    CGContextSaveGState(CGContextRef)以及CGContextRestoreGState(CGContextRef)两个函数存储当前绘图环境(包括坐标系统,绘图属性)以及恢复上次储存的绘图环境

     

    坐标多次变化操作

    - (void)drawRect:(CGRect)rect
    {
        //获取图像上下文对象
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        UIImage *image = [UIImage imageNamed:@"girl.jpg"];
        
        CGContextSaveGState(context);
        CGContextScaleCTM(context, 0.5,0.5);
        [image drawInRect:rect];
        CGContextRestoreGState(context);
        
        CGContextSaveGState(context);
        CGContextTranslateCTM(context,rect.size.width/2, -rect.size.height/2);
        [image drawInRect:rect];
        CGContextRestoreGState(context);
    }

    坐标按原点旋转,通过将原点平移到屏幕中心可以实现图片绕中心旋转

    - (void)drawRect:(CGRect)rect
    {
        //获取图像上下文对象
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        UIImage *image = [UIImage imageNamed:@"girl.jpg"];
        
        CGContextTranslateCTM(context,rect.size.width/2, rect.size.height/2);
        CGContextRotateCTM(context, -180 * M_PI / 180);
        [image drawInRect:CGRectMake(0 - rect.size.width/2, 0 - rect.size.height/2, rect.size.width, rect.size.height)];
    }

    除了使用上面三个坐标变换方法,还可以使用CGContextConcatCTM(CGContextRef,CGAffineTransform)进行坐标转换,该方法需要创建CGAffineTransform,它代表一个3*3的变换矩阵,可以实现2维坐标所有的变换。

    关于CGAffineTransform的原理以及用法可以参考这篇博客

  • 相关阅读:
    修改MySQL数据文件的位置
    服务名无效。请键入 NET HELPMSG 2185 以获得更多的帮助。
    索引的讲解
    运行php程序时,浏览器跳出打开和保存提示框
    ora-4031错误
    MySQL_Oracle_事物的隔离级别
    GNU与Linux
    计算机网络_第一章
    Linux网卡高级命令
    Linux RAID简介
  • 原文地址:https://www.cnblogs.com/zanglitao/p/4035655.html
Copyright © 2011-2022 走看看