Android旋转动画

时间:2015-04-23 02:03:32

标签: android

我正在研究一个简单的罗盘应用程序。我正在使用旋转动画旋转图像但是当我从0度旋转到360度时,图像会翻转回来以0度重新开始。如何阻止图像向后旋转到0度。

float[] mGravity;
float[] mGeomagnetic;
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        mGravity = lowPass(event.values, mGravity);
    if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        mGeomagnetic = lowPass(event.values, mGeomagnetic);
    if (mGravity != null && mGeomagnetic != null) {
        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);

            //Convert azimuth to degrees
            float azimuthInDegrees = (float) (Math.toDegrees(orientation[0])+360)%360;


            //Show coord name
            String coordNames[] = {"N","NNE", "NE","ENE","E", "ESE","SE","SSE", "S","SSW", "SW","WSW", "W","WNW", "NW","NNW", "N"};
            double directionid = Math.round(azimuthInDegrees / 22.5);
            // no of array contain 360/16=22.5
            if (directionid < 0) {
                directionid = directionid + 16;
                //no. of contains in array
            }
            String compasLoc = coordNames[(int) directionid];

            tvHeading.setText("Heading: " + Float.toString(Math.round(azimuthInDegrees)) + " " + compasLoc);

            // create a rotation animation (reverse turn degree degrees)
            RotateAnimation ra = new RotateAnimation(
                    currentDegree,
                    -azimuthInDegrees,
                    Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF,
                    0.5f);

            // how long the animation will take place
            ra.setDuration(210);
            // set the animation after the end of the reservation status
            ra.setFillAfter(true);
            // Start the animation
            image.startAnimation(ra);
            currentDegree = -azimuthInDegrees;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

I test your animation code with a static toDegrees value

RotateAnimation ra = new RotateAnimation(
    15,
    -30, // a static vaule
    Animation.RELATIVE_TO_SELF,
    0.5f,
    Animation.RELATIVE_TO_SELF,
    0.5f);

and the image rotate to right degree, the code snippet works normally. You should add log to debug how startAnimation is invoked. Maybe onSensorChanged(SensorEvent event) is invoked again and cause the image rotate backwards.

相关问题