變換(transformation)

運用變換 

變換(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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章