Android中的翻轉動畫效果的實現,首先看一下運行效果如下圖所示.
Android中並沒有提供直接做3D翻轉的動畫,所以關於3D翻轉的動畫效果需要我們自己實現,那麼我們首先來分析一下Animation 和 Transformation。
Animation動畫的主要接口,其中主要定義了動畫的一些屬性比如開始時間,持續時間,是否重復播放等等。而Transformation中則包含一個矩陣和alpha值,矩陣是用來做平移,旋轉和縮放動畫的,而alpha值是用來做alpha動畫的,要實現3D旋轉動畫我們需要繼承自Animation類來實現,我們需要重載getTransformation和applyTransformation,在getTransformation中Animation會根據動畫的屬性來產生一系列的差值點,然後將這些差值點傳給applyTransformation,這個函數將根據這些點來生成不同的Transformation。下面是具體實現:
package com.example.textviewtest;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class Rotate3dAnimation extends Animation {
// 開始角度
private final float mFromDegrees;
// 結束角度
private final float mToDegrees;
// 中心點
private final float mCenterX;
private final float mCenterY;
private final float mDepthZ;
// 是否需要扭曲
private final boolean mReverse;
// 攝像頭
private Camera mCamera;
public Rotate3dAnimation(float fromDegrees, float toDegrees, float centerX,
float centerY, float depthZ, boolean reverse) {
mFromDegrees = fromDegrees;
mToDegrees = toDegrees;
mCenterX = centerX;
mCenterY = centerY;
mDepthZ = depthZ;
mReverse = reverse;
}
@Override
public void initialize(int width, int height, int parentWidth,
int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mCamera = new Camera();
}
// 生成Transformation
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final float fromDegrees = mFromDegrees;
// 生成中間角度
float degrees = fromDegrees
+ ((mToDegrees - fromDegrees) * interpolatedTime);
final float centerX = mCenterX;
final float centerY = mCenterY;
final Camera camera = mCamera;
final Matrix matrix = t.getMatrix();
camera.save();
if (mReverse) {
camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
} else {
camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
}
camera.rotateY(degrees);
// 取得變換後的矩陣
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
}