2014-09-27 34 views
-1

我想用仿射變換旋轉矩形45度。我知道我必須移動上下文以使得矩形在原點處,應用旋轉然後向後移動。我想完全理解這是如何工作的,所以我開始了一個小測試,圍繞原點(父視圖的座標系中的0,0)旋轉它,而不是回退。這是被翻譯到原點後視圖(在這種情況下,綠色矩形):如何通過仿射變換在原點周圍應用旋轉

enter image description here

然後轉動10度,它看起來像這樣:

enter image description here

我希望它以原點爲軸心,但是這看起來也是翻譯的原點,所以當我應用旋轉時,它看起來就像我將它應用於舊位置一樣,只是轉換爲其他點。我錯過了什麼?

這是代碼...

- (void)drawRect:(CGRect)rect { 

    CGContextRef context = UIGraphicsGetCurrentContext(); 


    UIColor * redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0]; 
    float x = 150; 
    float y = 150; 
    float w = 120; 
    float h = 40; 

    CGRect r = CGRectMake(x, y, w, h); 
    CGContextSetFillColorWithColor(context, redColor.CGColor); 
    CGContextFillRect(context, r); 

    CGContextSaveGState(context); 


    NSLog(NSStringFromCGRect(self.frame)); 

    //move to the origin 
    CGAffineTransform transform = CGAffineTransformMakeTranslation(-x, -y); 
    float rad = DEGREES_TO_RADIANS(10); //with 45 it's outside of the view 

    CGFloat rotation = rad; 

    //rotate 
    transform = CGAffineTransformRotate(transform, rotation); 

    CGContextConcatCTM(context, transform); 

    r = CGRectMake(x, y, w, h); 
    CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor); 
    CGContextFillRect(context, r); 

    CGContextRestoreGState(context); 
    } 
+0

這是爲什麼downvoted? – Ixx 2014-09-28 18:55:54

回答

0

我發現這個問題。轉換以相反的順序應用,因此它將首先旋轉,然後進行翻譯。

如果我改變這樣的:

- (void)drawRect:(CGRect)rect { 

    CGContextRef context = UIGraphicsGetCurrentContext(); 


    UIColor * redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0]; 
    float x = 150; 
    float y = 150; 
    float w = 120; 
    float h = 40; 

    CGRect r = CGRectMake(x, y, w, h); 
    CGContextSetFillColorWithColor(context, redColor.CGColor); 
    CGContextFillRect(context, r); 

    CGContextSaveGState(context); 


    NSLog(NSStringFromCGRect(self.frame)); 

    CGAffineTransform transform = CGAffineTransformIdentity; 

    float rad = DEGREES_TO_RADIANS(10); 

    CGFloat rotation = rad; 

    //rotate 
    transform = CGAffineTransformRotate(transform, rotation); 
    transform = CGAffineTransformTranslate(transform, -x, -y); 

    CGContextConcatCTM(context, transform); 

    r = CGRectMake(x, y, w, h); 
    CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor); 
    CGContextFillRect(context, r); 

    CGContextRestoreGState(context); 
} 

然後,它的工作原理:

enter image description here

相關問題