Joshua
Joshua

Reputation: 15500

Rotate UIImageView Depending on iPhone Orientation

How would I do this, all I want to do is rotate a UIImageView depending on the orientation of the iPhone.

Upvotes: 8

Views: 4258

Answers (1)

mvds
mvds

Reputation: 47034

You can do this through IB, to get an app with a portrait and a landscape layout, or you can do it programmatically. This is about the programmatic way.

To get notifications on the change of orientation, use

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
                selector:@selector(orientationChanged)
                name:UIDeviceOrientationDidChangeNotification
                object:nil];

and add a function like this (note this is copypasted from a project and a lot of lines are left out, you will need to tune the transformation to your specific situation)

-(void)orientationChanged
{
    UIDeviceOrientation o = [UIDevice currentDevice].orientation;

    CGFloat angle = 0;
    if ( o == UIDeviceOrientationLandscapeLeft ) angle = M_PI_2;
    else if ( o == UIDeviceOrientationLandscapeRight ) angle = -M_PI_2;
    else if ( o == UIDeviceOrientationPortraitUpsideDown ) angle = M_PI;

    [UIView beginAnimations:@"rotate" context:nil];
    [UIView setAnimationDuration:0.7];
    self.rotateView.transform = CGAffineTransformRotate(
                                CGAffineTransformMakeTranslation(
                                    160.0f-self.rotateView.center.x,
                                    240.0f-self.rotateView.center.y
                                ),angle);
    [UIView commitAnimations];
}

When you're done, stop the notifications like so:

[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] removeObserver:self];

Upvotes: 18

Related Questions