Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate UIView around its center keeping its size

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; 

enter image description here

Thanks!

like image 707
Diego Acosta Avatar asked Jan 26 '14 23:01

Diego Acosta


2 Answers

I avoid using macros unless necessary. This works perfectly well

float degrees = 20; //the value in degrees view.transform = CGAffineTransformMakeRotation(degrees * M_PI/180); 
like image 148
Shaheen Ghiassy Avatar answered Sep 20 '22 13:09

Shaheen Ghiassy


Swift + extension are your friends!

// MARK: - UIView Extension -  extension UIView {      /**      Rotate a view by specified degrees       - parameter angle: angle in degrees      */     func rotate(angle: CGFloat) {         let radians = angle / 180.0 * CGFloat.pi         let rotation = CGAffineTransformRotate(self.transform, radians);         self.transform = rotation     }  } 

In this way, anywhere in your code:

let view = UIView(frame: CGRectMake(0, 0, 100, 100)) view.backgroundColor = UIcolor.redColor() view.rotate(angle: 90) 
like image 32
Luca Davanzo Avatar answered Sep 17 '22 13:09

Luca Davanzo