IOS影像處理(4)座標變化

來源:互聯網
上載者:User

標籤: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)座標變化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.