1
votes

I'm trying to rotate a line (which is nothing more than a UIView) around it's origin. For the rotation I'm using CGAffineTransformRotate but I know this will rotate the line around it's center. To change the rotation point I'm using CGAffineTransformTranslate. Despite this the line is not rotating correctly. What am I doing wrong? Here is my code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView *testView = [[UIView alloc] initWithFrame:CGRectMake(300, 400, 300, 3)];
    testView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:testView];

    testView.transform = CGAffineTransformTranslate(testView.transform, -150, 0);
    testView.transform = CGAffineTransformRotate(testView.transform, 45 * M_PI / 180);
}

Thanks in advance

1

1 Answers

1
votes

This has happened to me before and the answer is not obvious but it's very simple. The problem is that you're not restoring the view's "rotation point". For some reason this makes the rotation not work the way you want.

Here is what you have to do to fix the problem:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView *testView = [[UIView alloc] initWithFrame:CGRectMake(300, 400, 300, 3)];
    testView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:testView];

    testView.transform = CGAffineTransformTranslate(testView.transform, -150, 0);
    testView.transform = CGAffineTransformRotate(testView.transform, 45 * M_PI / 180);

    // Restore the rotation point. This will fix your issue.
    testView.transform = CGAffineTransformTranslate(testView.transform, 150, 0);
}

Hope this helps!