標籤:style blog http color io os ar 使用 for
在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的原理以及用法可以參考這篇部落格
IOS影像處理(4)座標變化