无论设备方向如何,如何让UIView指向某个方向?

时间:2011-02-02 04:20:48

标签: iphone ios core-animation uiaccelerometer

我有一个UIView,我想永远面对。所以说你有一个带有箭头的UIImageView,无论设备被保持在什么状态,它都指向上方。显然我需要加速度计,但是告诉它根据坐标旋转图像只会在我想到的第一次工作,因为旋转是相对的。有更简单的方法吗?我觉得在某个地方会有一个简单的示例应用程序会做这样的事情。

3 个答案:

答案 0 :(得分:3)

Apple提供的示例代码完全符合您的要求;看看这个:http://developer.apple.com/library/ios/#samplecode/WhichWayIsUp/Introduction/Intro.html

要接收特定的动作数据,请使用UIAccelerometer的共享实例及其委托。 http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAccelerometerDelegate_Protocol/UIAccelerometerDelegate/UIAccelerometerDelegate.html#//apple_ref/occ/intf/UIAccelerometerDelegate

就轮换而言,我不确定。在这里查看“BubbleLevel”示例代码:http://developer.apple.com/library/ios/samplecode/BubbleLevel/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007331

加速计代表文档引用了该代码和其他相关示例代码。

答案 1 :(得分:0)

WhichWayIsUp是您正在寻找的示例应用程序 - 在iOS参考库中(很棒的文档!)

答案 2 :(得分:0)

应用于视图的变换不是累积的。相反,视图开始与其父节点的坐标系对齐,并且相对于该节点应用变换。

正如其他答案所暗示的那样,Apple的BubbleLevel sample code中有足够多的内容可以帮助您实现所需的目标。 -[LevelViewController accelerometer:didAccelerate:]已经包含了如何提取重力矢量的平滑屏幕相对旋转分量的示例:

// Use a basic low-pass filter to only keep the gravity in the accelerometer values for the X and Y axes
accelerationX = acceleration.x * kFilteringFactor + accelerationX * (1.0 - kFilteringFactor);
accelerationY = acceleration.y * kFilteringFactor + accelerationY * (1.0 - kFilteringFactor);

// keep the raw reading, to use during calibrations
currentRawReading = atan2(accelerationY, accelerationX);

鉴于UIAccelerationatan2的坐标系,您需要记住几个因素来计算视图的所需旋转:

  1. 当设备竖直竖立时,atan2将返回-π/ 2(-90°),因为输入重力矢量为{0.0,-1.0,0.0}。
  2. CGAffineTransformMakeRotation创建一个转换,按顺时针方向(在iOS上)按指定的弧度数旋转,但atan2的原始角度指定逆时针旋转。
  3. 因此,您需要通过 - (currentRawReading +π/ 2)旋转您的视图,假设其父视图以屏幕为纵向定向:

    view.transform = CGAffineTransformMakeRotation(-(currentRawReading + M_PI/2));