Android X轴Y轴Z轴旋转

Android中并没有提供直接做3D翻转的动画,所以关于3D翻转的动画效果需要我们自己实现,一个简单的办法就是重写Animation。这里只是以Y轴旋转进行下说明,至于X轴、Z轴和Y轴的原理是一样的。先看下效果图
这里写图片描述

具体实现代码:

public class MyAnimation extends Animation {
    int centerX, centerY;
    Camera camera = new Camera();

    @Override
    public void initialize(int width, int height, int parentWidth,
            int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        //获取中心点坐标
        centerX = width / 2;
        centerY = height / 2;
        //动画执行时间  自行定义
        setDuration(1200); 
        setInterpolator(new DecelerateInterpolator()); 
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final Matrix matrix = t.getMatrix();
        camera.save(); 
        //中心是绕Y轴旋转  这里可以自行设置X轴 Y轴 Z轴
        camera.rotateY(360 * interpolatedTime); 
        //把我们的摄像头加在变换矩阵上
        camera.getMatrix(matrix);
        //设置翻转中心点 
        matrix.preTranslate(-centerX, -centerY); 
        matrix.postTranslate(centerX, centerY);
        camera.restore(); 
    }
}

具体使用方法如下:

MyAnimation animation = new MyAnimation ();
animation.setRepeatCount(10);
view.startAnimation(animation); 

可以发现定义和使用都比较简单,这里简单说下animation里面的preTranslate和postTranslate方法,preTranslate是指在rotateY前平移,postTranslate是指在rotateY后平移,注意他们参数是平移的距离,而不是平移目的地的坐标!

由于旋转是以(0,0)为中心的,所以为了把界面的中心与(0,0)对齐,就要preTranslate(-centerX, -centerY), rotateY完成后,调用postTranslate(centerX, centerY),再把图片移回来,这样看到的动画效果就是activity的界面图片从中心不停的旋转了。

猜你喜欢

转载自blog.csdn.net/mixin716/article/details/50318635