Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate UIImageView with same center point using CGAffineTransformMakeRotation

I'm trying to rotate a UIImageView and keep it centered. In the image below I would like the rotated arrow (red crosshairs) center point to match up with the center point of the 0° arrow (blue crosshairs).

I have tried various anchor points but I can't seem to get it to behave as I want.

// Rotate
self.arrowRotatedImageView.layer.anchorPoint = CGPointMake(0.5,0.5);
CGFloat angle = 45 * (M_PI/180);
self.arrowRotatedImageView.transform = CGAffineTransformMakeRotation(angle);

What am I missing? I'm reading through the Apple docs but I haven't been able to figure it out.

iPhone screenshot of a rotated arrow on top of a non-rotated arrow

like image 723
Matt Morey Avatar asked Nov 22 '12 15:11

Matt Morey


2 Answers

Turns out the weird rotation issue was related to the new iOS 6 autolayout feature. Once I took some time to understand how the align constraints worked I was able to achieve the results I wanted.

If you run into weird rotation issues and are using iOS 6 with autolayout enabled chances are your constraints need adjusting.

The key is to vertically and horizontally center the image under rotation in it's parent view.

like image 167
Matt Morey Avatar answered Nov 15 '22 03:11

Matt Morey


I ran into the same problem, I solved it by applying a Center X Alignment Constraint and a Center Y Alignment Constraint to the UIImageView in question. Doing this will stop the image from moving away from its center x and y position.

like image 20
Cloud9999Strife Avatar answered Nov 15 '22 04:11

Cloud9999Strife