如何将箭头仅指向特定方向,即向西

时间:2019-09-03 13:28:02

标签: android math sensor compass compass-geolocation

无论用户面向何处,我都希望将箭头视图仅指向西方向。下面是我尝试过但未获得预期结果的代码。

// inside onCreate()
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    msensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    packageManager = getPackageManager();
    if (packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)){
        sensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_GAME);
    }else {
        Toast.makeText(MainActivity.this,"No Compass Sensor !", Toast.LENGTH_SHORT).show();
    }


 @Override
public void onSensorChanged(SensorEvent event) {

    final float alpha = 0.97f;

    synchronized (this){
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
            mGravity[0] = alpha * mGravity[0] + (1 - alpha)
                    * event.values[0];
            mGravity[1] = alpha * mGravity[1] + (1 - alpha)
                    * event.values[1];
            mGravity[2] = alpha * mGravity[2] + (1 - alpha)
                    * event.values[2];
        }

        if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
            mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha)
                    * event.values[0];
            mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha)
                    * event.values[1];
            mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha)
                    * event.values[2];
        }

        float R[] = new float[9];
        float I[] = new float[9];
        boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
        if (success){
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);
            azimuth = (float) Math.toDegrees(orientation[0]);
            Log.i("DegreeA",""+azimuth);
            azimuth = (azimuth + 360) % 270;
            Log.i("DegreeA",""+azimuth);
            adjustThearrow();
        }
    }
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

private void adjustThearrow(){


    Matrix matrix = new Matrix();
    imageview.setScaleType(ImageView.ScaleType.MATRIX);   
    matrix.postRotate((float) -azimuth, imageview.getDrawable().getBounds().width()/2,
            imageview.getDrawable().getBounds().height()/2);

    imageview.setImageMatrix(matrix);
}

在下面的代码行中,如果我将360设置为270,而不是270,则它使我仅向北指向箭头,并且旋转平稳。

azimuth = (azimuth + 360) % 360;

但是,如果我希望我的代码仅将箭头指向西方向,则可以这样设置代码:

azimuth = (azimuth + 360) % 270;

但是这次旋转并不平滑。

请帮助我进行操作。最好提供其他替代解决方案。

0 个答案:

没有答案