I'm trying to rotate an UIView
a few radians but after applying the transformation it doesn't look to be keeping its size. What's the proper way to achieve this?
Here's what I'm doing and what I get (Blue box with the arrow is the View I'm trying to rotate -- it should keep same aspect as red box behind):
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
double rads = DEGREES_TO_RADIANS(240);
CGAffineTransform transform = CGAffineTransformRotate(CGAffineTransformIdentity, rads);
self.arrowView.transform = transform;
Thanks!
To my mind you need to calculate the center of your triangle and rotate around this point. Now you rotate the arrow around the center of your square.
See: One step affine transform for rotation around a point?
I Hope it will help you.
On Swift 3:
I'm using
-90
because of this specific part of the documentation about therotationAngle
you have to pass toCGAffineTransform
:I avoid using macros unless necessary. This works perfectly well
Update Luca Davanzo's answer with Swift 4:
Swift + extension are your friends!
In this way, anywhere in your code:
You're probably hitting a problem with Autolayout. You probably have constraints on the rotated view pinning it to the edges of the superview. When the transform is applied, Autolayout is updating the view's size to still fit within the superview.
You can experiment with different constraints (e.g. pinning the centre of the view to the centre of another view, and pinning the width and height to constant values) or turn Autolayout off for the rotated view, or, if these don't work or don't suit your needs, use a container view which is laid out under Autolayout, and add your rotating view to this, without using Autolayout.
This can only be done in code - you can make individual views subject to Autolayout or not by setting
translatesAutoresizingMasksIntoConstraints
toNO
(Autolayout on) orYES
(Autolayout off). You'll need to set the appropriate autoresizing masks if you switch a view from one to the other.