在Android中,可以使用android.graphics.Camera這個(gè)類進(jìn)行3D變換
之前更改CameraUI的時(shí)候,需要做一個(gè)切換前后攝像頭的翻轉(zhuǎn)動(dòng)畫,剛開(kāi)始在網(wǎng)上著了一些翻轉(zhuǎn)動(dòng)畫的代碼,合到自己的代碼之后,發(fā)現(xiàn)并沒(méi)有達(dá)到自己想要的效果,為此糾結(jié)了很久,后來(lái)湊巧把幾份Demo代碼揉雜在一起,突然發(fā)現(xiàn)達(dá)到了理想效果。。暈,逐行閱讀代碼,原因還是細(xì)節(jié)處理問(wèn)題--呵呵
下面貼出關(guān)鍵代碼
public class FlipAnimation extends Animation {
private Camera mCamera;
private float centerX;
private float centerY;
private float scale = 0.5f;
public FlipAnimator() {
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
// 初始化Camera,并得View X和Y軸的中心點(diǎn)坐標(biāo)
mCamera = new Camera();
centerX = width / 2;
centerY = height / 2;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final double radians = Math.PI * interpolatedTime;
float degrees = (float) (180.0 * radians / Math.PI);
if (interpolatedTime >= 0.5f) {
degrees -= 180.f;
}
//利用Matrix 對(duì)view進(jìn)行平移,縮放等變換
final Matrix matrix = t.getMatrix();
camera.save();
// 根據(jù)動(dòng)畫播放進(jìn)度,在Z軸方向進(jìn)行平移,達(dá)到先遠(yuǎn)離屏幕,在靠近屏幕的效果
camera.translate(0.0f, 0.0f, (float) (300.0 * Math.sin(radians)));
// 圍繞X軸進(jìn)行旋轉(zhuǎn)
camera.rotateX(degrees);
// 圍繞Y軸進(jìn)行旋轉(zhuǎn),此處是實(shí)現(xiàn)上下翻轉(zhuǎn),因此不要Y軸變換
//camera.rotateY(degrees);
//圍繞Z軸進(jìn)行旋轉(zhuǎn),此處是實(shí)現(xiàn)上下翻轉(zhuǎn),因此不要Z軸變換
//camera.rotateZ(degrees);
camera.getMatrix(matrix);
camera.restore();
// 下面兩行代碼是設(shè)置旋轉(zhuǎn)中心點(diǎn)為圖像正中
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
// 對(duì)圖像進(jìn)行縮放
matrix.preScale(scale, scale, centerX, centerY);
}
}
由于我需要翻轉(zhuǎn)的是整個(gè)屏幕界面,僅僅是上下翻轉(zhuǎn),會(huì)導(dǎo)致翻轉(zhuǎn)的時(shí)候上半部分或下半部分超出屏幕(根據(jù)動(dòng)畫的方向決定:從上至下/從下至上),動(dòng)畫看起來(lái)會(huì)很奇怪,因此最重要的是要加上縮小和Z軸平移效果
camera.translate(0.0f, 0.0f, (float) (300.0 * Math.sin(radians)));
matrix.preScale(scale, scale, centerX, centerY);
將View縮在屏幕范圍內(nèi)進(jìn)行3D變換,看起來(lái)perfect(貌似你們看不到,哈哈)
使用動(dòng)畫的方法就簡(jiǎn)單了
view.startAnimation(new FlipAnimation())就可以了