代码之家  ›  专栏  ›  技术社区  ›  Joshua

根据iPhone方向旋转UIImageView

  •  8
  • Joshua  · 技术社区  · 16 年前

    我要怎么做,我只想旋转一个 UIImageView

    1 回复  |  直到 16 年前
        1
  •  18
  •   mvds    14 年前

    你可以通过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];