1

When I am trying to rotate a view in iOS its coordinates changed.

I want to rotate a rectangle view 90 degree, but my problem is that the view does not located in its frame correctly after rotation .

self.frame = CGRectMake(0, 0, screenWidth, screenHeight);
  NSLog(@"BEFORE %@", NSStringFromCGRect(self.frame));

 self.transform = CGAffineTransformMakeRotation(M_PI_2);

 NSLog(@"AFTER %@", NSStringFromCGRect(self.frame));

here is the Log

     BEFORE {{0, 0}, {414, 636}}
     AFTER {{-161, 160.99999999999997}, {636, 414}}

U can see that the X and Y coordinates has changed, this leads the view to be sets incorrectly on its container. I cant understand the formula of changing them to be considered when setting the frame .

Ahd Radwan
  • 1,090
  • 4
  • 14
  • 31
  • the problem is with the anchor points [here](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreAnimation_guide/CoreAnimationBasics/CoreAnimationBasics.html) is a guide about anchor points – Umair Afzal May 26 '16 at 06:13
  • i wish i remember those trigonometry rules ! – maddy May 26 '16 at 06:23
  • check with bounds property as per apple https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instp/UIView/frame – maddy May 26 '16 at 06:37

2 Answers2

1

I have an app in which I rotate a view (myView) exactly as you want. I do this :

#define DegreesToRadians(x) ((x) * M_PI / 180.0)
CGRect rect = myView.frame;
myView.transform = CGAffineTransformMakeRotation(DegreesToRadians(-90));
myView.frame = CGRectMake(
    rect.origin.x, 
    rect.origin.y,   
    rect.size.height, 
    rect.size.width  // notice that Width and height are interchanged
    );

Remember that when you rotate the view, it will rotate around its origin, not around its center. So you have to compute the new origin and size of the view after it has rotated, according to your needs.

Or just reapply correct origin point and width/height that you stored in "rect", as I do.

Chrysotribax
  • 789
  • 1
  • 9
  • 17
0

Try use bounds in proper way:

self.frame = CGRectMake(0, 0, screenWidth, screenHeight);
  NSLog(@"BEFORE %@", NSStringFromCGRect(self.frame));

 self.transform = CGAffineTransformMakeRotation(M_PI_2);


self.frame = CGRectMake(0, 0, 
    CGRectGetWidth(self.bounds), 
    CGRectGetHeight(self.bounds)); 
 NSLog(@"AFTER %@", NSStringFromCGRect(self.frame));

Hope it helps !!

maddy
  • 4,001
  • 8
  • 42
  • 65