【问题标题】:Calculate X orientation value with device orientation使用设备方向计算 X 方向值
【发布时间】:2013-05-22 13:01:08
【问题描述】:

我有一个应用程序,它显示用加速度计和磁力计计算的 x、y、z 方向值。但是当我从纵向切换到横向时,我没有得到相同的 X 值。我尝试使用旋转矢量来实现,但我的设备没有旋转矢量传感器:s

这是我计算 X、Y、Z 值的代码:

@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    float x, y, z;
    String s1 = "stringX", s2 = "stringY", s3 = "stringZ";
    // Mettre à jour la valeur de l'accéléromètre et du champ magnétique
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        acceleromterVector=event.values;
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
        magneticVector=event.values;
    }
    // Demander au sensorManager la matrice de Rotation (resultMatrix)
    SensorManager.getRotationMatrix(resultMatrix, null, acceleromterVector, magneticVector);
    // Demander au SensorManager le vecteur d'orientation associé (values)
    SensorManager.getOrientation(resultMatrix, values);
    // l'azimuth
    x = (float) Math.toDegrees(values[0]);
    // le pitch
    y = (float) Math.toDegrees(values[1]);
    // le roll
    z = (float) Math.toDegrees(values[2]);


    s1 = "X :" + x;
    s2 = "Y :" + y;           
    s3 = "Z :" + z;

    tvx.setText(s1);
    tvy.setText(s2);
    tvz.setText(s3);

    updateOrientation(x);
}

谢谢你们。

【问题讨论】:

    标签: android android-sensors android-orientation device-orientation


    【解决方案1】:

    传感器值始终与默认方向相关,因此您需要考虑远离默认方向的旋转。为此,请使用以下内容:

    int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    float screen_adjustment = 0;
    switch(rotation) {
        case Surface.ROTATION_0:   screen_adjustment =          0;         break;
        case Surface.ROTATION_90:  screen_adjustment =   (float)Math.PI/2; break;
        case Surface.ROTATION_180: screen_adjustment =   (float)Math.PI;   break;
        case Surface.ROTATION_270: screen_adjustment = 3*(float)Math.PI/2; break;
    }
    

    调整方位角。如需完整的示例,请参阅the code that I posted in my answer here

    【讨论】:

    • 您的完整示例看起来很有趣,但有点难。如果我处理这个屏幕调整,我必须做方位角 + 屏幕调整以获得正确的方位角值?
    • 确实,只要您的设备平放在桌子上,我希望 azimuth + screen_adjustment 能够为您提供正确的方位角。当设备直立时,来自SensorManager.getOrientation 的方位角开始出现异常,这就是我的示例。
    • 这对我来说不合逻辑随机,我的 X 基本值为 85,如果我添加 1.5(即 PI/2)的调整,它不会改变我移动的方向从 0 -> 360°。我希望你能理解我:x
    • 我的代码中的屏幕调整在radians。对于度数,将我的 switch 语句中的 4 种情况分别更改为 0、90、180、270 而不是 0、pi/2、pi 和 3*pi/2。
    • 我查看了您链接上的代码,如何调整滚动?随机谢谢。
    猜你喜欢
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 2013-10-10
    相关资源
    最近更新 更多