0

我有一个应用程序,它显示用加速度计和磁力计计算出的x,y,z方向值。但是当我从肖像换成风景时,我没有得到相同的X值。我tryed,带有旋转矢量来实现,但我的设备没有旋转矢量传感器:■用设备方向计算X方向值

这里是我的代码来计算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); 
} 

谢谢你们。

回答

0

传感器值始终相对于默认方向,因此您需要考虑远离默认方向的旋转。要做到这一点,请使用以下内容:

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

调整azimith。有关完整的示例,请参阅the code that I posted in my answer here

+0

你完全的例子看起来很有趣,但有点难。 如果我处理这个screen_adjustment,我必须做方位角+屏幕调整才能获得正确的方位角值? – Eydolol

+0

事实上,只要您的设备躺在桌子上靠近平面,我会希望方位角+ screen_adjustment为您提供正确的方位角。当设备直立时,来自'SensorManager.getOrientation'的方位开始行为异常,这就是我的例子。 – Stochastically

+0

这对我来说不合逻辑的,如果我加上1.5(这是PI/2)的调整值,我对X有85的基本值,它不会改变我的方向,从0-> 360°移动。我希望你能理解我:x – Eydolol