变换(transformation)

来源:互联网 发布:精易编程助手教程 编辑:程序博客网 时间:2024/06/08 12:14

运用变换 

变换(transformation)修改了图形上下文中绘制图形的方式。可以通过移动、旋转或缩放实现变换。

Quartz提供了多种形式的变换,其中主要:CTM(当前变换矩阵)变换和仿射(affine)变换。

CTM(current transformation matrix)变换,这种变换比较简单,函数有:

CGContextRotateCTM,旋转坐标

CGContextScaleCTM,缩放坐标

CGContextTranslateCTM,移动原点

移动变换

CGContextTranslateCTM (myContext, 100, 50)

wps_clip_image-23595

从对象角度沿着x轴正向移动100单位,沿着y轴正向移动50单位。

旋转变换

static inline double radians (double degrees) {return degrees * M_PI/180;}

CGContextRotateCTM (myContext, radians(–45.));

wps_clip_image-9368

从对象角度:

在Quartz坐标下正数为逆时针旋转,负数为顺时针旋转。

在UIKit坐标下正数为顺时针旋转,负数为逆时针旋转。

缩放变换

CGContextScaleCTM (myContext, .5, .75);

wps_clip_image-14003

从对象角度:所有x坐标缩小0.5,所有y坐标缩小0.75。

修改MyView.m文件

复制代码
#import "MyView.h"@implementation MyView- (void)drawRect:(CGRect)rect {    NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"jpg"];    UIImage *img = [UIImage imageWithContentsOfFile:path];    CGImageRef image = img.CGImage;    CGContextRef context = UIGraphicsGetCurrentContext();    CGContextSaveGState(context);        CGContextRotateCTM(context, M_PI);    CGContextTranslateCTM(context, -img.size.width, -img.size.height);        CGRect touchRect = CGRectMake(0, 0, img.size.width, img.size.height);    CGContextDrawImage(context, touchRect, image);      CGContextRestoreGState(context);}@end
复制代码

 

仿射(affine)变换

仿射(affine)变换也是一种直角坐标变换,重

用变换,经过多次变换(多次的矩阵相乘),

每一种变换都可以用矩阵表示,通过多次矩阵

相乘得到最后结果。仿射变换函数:

    CGAffineMakeRotation,创建旋转矩阵仿射对象

    CGAffineMakeScale,创建缩放矩阵仿射对象

    CGAffineMakeTranslation,创建移动矩阵仿射对象

    CGAffineTransformRotate,旋转矩阵仿射对象

    CGAffineTransformScale,缩放矩阵仿射对象

    CGAffineTransformTranslate,移动矩阵仿射对象

    CGContextConcatCTM,连接到CTM变换

使用仿射变换MyView.m

复制代码
#import "MyView.h"@implementation MyView- (void)drawRect:(CGRect)rect {    NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"jpg"];    UIImage *img = [UIImage imageWithContentsOfFile:path];    CGImageRef image = img.CGImage;    CGContextRef context = UIGraphicsGetCurrentContext();    CGContextSaveGState(context);        CGAffineTransform myAffine = CGAffineTransformMakeRotation(M_PI);     myAffine = CGAffineTransformTranslate(myAffine, -img.size.width, -img.size.height);     CGContextConcatCTM(context, myAffine);        CGContextRotateCTM(context, M_PI);    CGContextTranslateCTM(context, -img.size.width, -img.size.height);        CGRect touchRect = CGRectMake(0, 0, img.size.width, img.size.height);    CGContextDrawImage(context, touchRect, image);      CGContextRestoreGState(context);}@end
0 0
原创粉丝点击