少年郎,是時候打造自己的第一款狂拽酷炫的3D效果了!
背景介紹
Android中有兩個Camera類。一個是android.hardware.Camera,用于對設(shè)備的攝像頭進行操作。另一個是android.graphics.Camera,可用于進行3D變換,然后把變換后的矩陣Matrix作用于Canvas等,我們本篇要介紹的就是這個Camera類。
玩轉(zhuǎn)Camera
前面我們提到過,Camera是一個能夠進行3D變化的類,在進行玩3D變換后,我們能夠通過mCamera.getMatrix(Matrix)把變換矩陣Matrix賦值,然后可以用在Canvas上?;蛘撸憧梢灾苯油ㄟ^mCamera.applyToCanvas(Canvas)直接把變換作用到一個Canvas上。
Android中的三維坐標軸
Android中的三維坐標軸符合左手坐標系。
Camera默認的位置是在(0, 0, -8)點。
Camera的變換操作
方法 | 說明 |
getMatrix(mMatrix) | 給mMatrix賦值。 |
applyToCanvas(mCanvas) | 將變換獲得的Matrix直接作用到mCanvas上。 |
rotate(x,y,z) | 旋轉(zhuǎn)。 |
rotateX、rotateY、rotateZ | 旋轉(zhuǎn)。 |
getLocationX、getLocationY、getLocationZ | 獲得Camera的位置,默認是在(0,0,-8)點。 |
setLocation(x,y,z) | 設(shè)置camera的位置。 |
translate(x,y,z) | 平移Camera。 |
save() | 與Canvas的類似。 |
restore() | 與Canvas類似。 |
Camera的方法并不多,所以使用起來也是比較簡單明了的。
Camera的使用實例
由于使用Camera的核心就是獲得一個變換后的Matrix,所以你需要對Matrix具有一定的認識。
演示Demo1
3D ViewGroup演示
Camera用于自定義動畫
直接上個代碼實例,用法和前面的例子沒什么本質(zhì)區(qū)別,都是通過Camera變換之后獲得Matrix矩陣。
- public class Custom3DAnimation extends Animation {
- private Camera mCamera;
- private int centerWidth;
- private int centerHeight;
- public void setmRotateY(float mRotateY) {
- this.mRotateY = mRotateY;
- }
- private float mRotateY;
- public Custom3DAnimation() {
- mCamera = new Camera();
- mRotateY = 90;
- }
- @Override
- protected void applyTransformation(float interpolatedTime, Transformation t) {
- Matrix matrix = t.getMatrix(); //獲得Transformation的Matrix
- mCamera.save();//保存當前鏡頭狀態(tài)
- mCamera.rotateY(mRotateY * interpolatedTime); //使相機旋轉(zhuǎn)
- mCamera.getMatrix(matrix); //將旋轉(zhuǎn)變換作用到matrix上
- mCamera.restore(); //合并鏡頭層
- matrix.preTranslate(centerWidth, centerHeight);//操作前平移
- matrix.postTranslate(-centerWidth, -centerHeight); //操作后平移
- }
- @Override
- public void initialize(int width, int height, int parentWidth, int parentHeight) {
- super.initialize(width, height, parentWidth, parentHeight);
- setDuration(5 * 1000); //設(shè)置默認持續(xù)時間
- setFillAfter(true); //設(shè)置動畫結(jié)束后是否保持狀態(tài)
- setInterpolator(new LinearInterpolator()); //設(shè)置插值器
- centerWidth = width / 2;
- centerHeight = height / 2;
- }
- }
總結(jié)
Camera的使用其實并不復(fù)雜,只需要記住前面提到的幾個方法就行。由于Camera最終是輸出一個矩陣,所以還需要對矩陣有一定的掌握。上面我已經(jīng)給出了矩陣快速使用的指南,大家可以根據(jù)情況自行參考。