Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate UIView by 45 degrees?

I want to rotate my UIButton by M_PI/4 with animation. Here's my code:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [UIView animateWithDuration:.5 animations:^{
        self.closeButton.transform = CGAffineTransformMakeRotation(M_PI/4);
    }];
}

But this make my button's frame corrupted. Frame before animation was (260 0; 44 44) and after animation it becomes (250.887 -9.1127; 62.2254 62.2254). I saw this post and few others, but I don't understand, how to achieve UIButton animated rotation by M_PI/2.

like image 940
Valentin Shamardin Avatar asked Mar 19 '14 16:03

Valentin Shamardin


People also ask

How do you rotate UIImage in Objective C?

You may rotate UIImageView itself with: UIImageView *iv = [[UIImageView alloc] initWithImage:image]; iv. transform = CGAffineTransformMakeRotation(M_PI_2); Or if you really want to change image, you may use code from this answer, it works.


2 Answers

The frame property is invalid once you've applied a transformation. According to the documentation:

Warning: If the transform property is not the identity transform, the value of this property is undefined and therefore should be ignored.

So as long as the result looks alright this is expected behavior.

If you want to move the button, you need to save the transformation, reset it to CGAffineTransformIdentity, set the new frame, then re-apply the old transformation. Alternatively, you may access and modify the center property of the frame even when a transformation is applied.

like image 50
DarkDust Avatar answered Oct 06 '22 00:10

DarkDust


The frame of a UIView is the smallest rectangle that fully encloses the view. When you rotate by PI/2 the frame will expand by sqrt(2), and the origin will be adjusted to keep the center at the same point, which is exactly what happened.

If you want the button to rotate and keep its same frame, you need to squash the button as it rotates, like this

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    CGFloat w = self.closeButton.bounds.size.width  / sqrtf( 2.0f );
    CGFloat h = self.closeButton.bounds.size.height / sqrtf( 2.0f );
    NSLog( @"%@ w=%f", NSStringFromCGRect( self.closeButton.bounds ), w );

    [UIView animateWithDuration:.5 animations:^{
        self.closeButton.transform = CGAffineTransformMakeRotation(M_PI/4);
        self.closeButton.bounds = CGRectMake( 0, 0, w, h );
    }];

    NSLog( @"%@", NSStringFromCGRect( self.closeButton.frame ) );
}
like image 23
user3386109 Avatar answered Oct 06 '22 00:10

user3386109