如何使用仿射变换在原点周围应用旋转

时间:2014-09-27 21:33:25

标签: ios objective-c

我想用仿射变换旋转45度。我知道我必须移动上下文,使得rect位于原点,应用旋转然后向后移动。我想完全理解它是如何工作的,所以我开始用一个小测试围绕原点旋转它(在父视图的坐标系中为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);
    }

1 个答案:

答案 0 :(得分: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