Matt Morey
Matt Morey

Reputation: 984

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

Upvotes: 5

Views: 3499

Answers (2)

Matt Morey
Matt Morey

Reputation: 984

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.

Upvotes: 6

Cloud9999Strife
Cloud9999Strife

Reputation: 3202

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.

Upvotes: 2

Related Questions