【问题标题】:Detect iPhone screen orientation检测 iPhone 屏幕方向
【发布时间】:2010-02-15 12:44:48
【问题描述】:

我想以 45 度的增量检测 iPhone 的方向。理想情况下,我希望能够获得沿任何轴的方向角度。

我需要做的检测类似于 iPhone 版 Trism 在方向改变时向屏幕当前底部位置闪烁的箭头。

我编写了一些代码,但我真的不明白加速度计读数是如何工作的,并且可以在正确的方向上使用轻推。我当前的代码记录了当前的角度,但即使手机是平放的,我的读数也会每秒发生几次剧烈变化。

- (void) checkOrientation:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{
    int accelerationX = acceleration.x * kfilteringFactor + accelerationX * (1.0 - kfilteringFactor);
    int accelerationY = acceleration.y * kfilteringFactor + accelerationY * (1.0 - kfilteringFactor);

    float currentRawReading = (atan2(accelerationY, accelerationX)) * 180/M_PI;
    NSLog(@"Angle: %f",currentRawReading);
}

手机没电时的日志样本:

2009-06-16 17:29:07.987 [373:207] Angle: 0.162292
2009-06-16 17:29:07.994 [373:207] Angle: 179.838547
2009-06-16 17:29:08.014 [373:207] Angle: 179.836182
2009-06-16 17:29:08.032 [373:207] Angle: -90.000000
2009-06-16 17:29:08.046 [373:207] Angle: 179.890900
2009-06-16 17:29:08.059 [373:207] Angle: -90.000000
2009-06-16 17:29:08.074 [373:207] Angle: 179.917908
2009-06-16 17:29:08.088 [373:207] Angle: -179.950424
2009-06-16 17:29:08.106 [373:207] Angle: 90.000000
2009-06-16 17:29:08.119 [373:207] Angle: 90.000000
2009-06-16 17:29:08.134 [373:207] Angle: -179.720245

【问题讨论】:

    标签: iphone orientation accelerometer


    【解决方案1】:

    我认为您的问题是您在需要 float 时使用了 int 变量。

    我认为accelerationX 和 –Y 应该是实例变量,因此:

    accelerationX = acceleration.x * kfilteringFactor + accelerationX * (1.0 - kfilteringFactor);
    accelerationY = acceleration.y * kfilteringFactor + accelerationY * (1.0 - kfilteringFactor);
    

    应该给你更多你想要的东西。

    【讨论】:

    • 感谢您的回复,我将代码更改为使用浮点数而不是整数,但是当设备平放时,我仍然得到计算值剧烈波动的结果。
    • 添加了一些从日志到问题的行。
    • 啊,第一次错过了关于实例变量的评论,看起来这可能是解决方案,会回复你。
    【解决方案2】:

    原因是您使用的是局部变量,而它们不应该是局部变量。

    尝试执行以下操作:

    声明实例变量:

    @interface YourViewControllerClass: UIViewController {
        float accelerationX, accelerationY;
    }
    
    ...
    
    other declarations
    

    更新加速度计委托中的变量:

     accelerationX = acceleration.x * kfilteringFactor + accelerationX * (1.0 - kfilteringFactor);
     accelerationY = acceleration.y * kfilteringFactor + accelerationY * (1.0 - kfilteringFactor);
    

    它应该给出更精确的结果,而不会突然跳跃。

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      相关资源
      最近更新 更多