根据iPhone方向旋转UIImageView

时间:2010-07-31 10:46:35

标签: iphone objective-c cocoa-touch

我该怎么做,我想做的就是根据iPhone的方向旋转UIImageView

1 个答案:

答案 0 :(得分:18)

您可以通过IB执行此操作,以获得具有纵向和横向布局的应用程序,或者您可以通过编程方式执行此操作。这是关于程序化的方式。

要获取有关方向更改的通知,请使用

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

并添加一个这样的函数(请注意,这是从项目中复制的,并且遗漏了很多行,您需要根据具体情况调整转换)

-(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];
}

完成后,请停止通知:

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