背景介紹
Android中有兩個(gè)Camera類。一個(gè)是android.hardware.Camera,用于對設(shè)備的攝像頭進(jìn)行操作。另一個(gè)是android.graphics.Camera,可用于進(jìn)行3D變換,然后把變換后的矩陣Matrix作用于Canvas等,我們本篇要介紹的就是這個(gè)Camera類。
玩轉(zhuǎn)Camera
前面我們提到過,Camera是一個(gè)能夠進(jìn)行3D變化的類,在進(jìn)行玩3D變換后,我們能夠通過mCamera.getMatrix(Matrix)
把變換矩陣Matrix賦值,然后可以用在Canvas上。或者,你可以直接通過mCamera.applyToCanvas(Canvas)
直接把變換作用到一個(gè)Canvas上。
Android中的三維坐標(biāo)系
Android中的三維坐標(biāo)軸符合左手坐標(biāo)系。需要注意,Android中的三維坐標(biāo)系中的Y軸和二維的是相反的。
Camera默認(rèn)的位置是在(0, 0, -8)點(diǎn)。
Camera的變換操作
方法 | 說明 |
---|---|
getMatrix(mMatrix) | 給mMatrix賦值。 |
applyToCanvas(mCanvas) | 將變換獲得的Matrix直接作用到mCanvas上。 |
rotate(x,y,z) | 旋轉(zhuǎn)。 |
rotateX、rotateY、rotateZ | 旋轉(zhuǎn)。 |
getLocationX、getLocationY、getLocationZ | 獲得Camera的位置,默認(rèn)是在(0,0,-8)點(diǎn)。 |
setLocation(x,y,z) | 設(shè)置camera的位置。 |
translate(x,y,z) | 平移Camera。 |
save() | 與Canvas的類似。 |
restore() | 與Canvas類似。 |
Camera的方法并不多,所以使用起來也是比較簡單明了的。
Camera的使用實(shí)例
由于使用Camera的核心就是獲得一個(gè)變換后的Matrix,所以你需要對Matrix具有一定的認(rèn)識(shí)。關(guān)于Matrix的入門級使用,可以參考一下我的這兩篇博客。
Android——Matrix變換矩陣的探索(1);
Android——Matrix變換矩陣的探索(2)
演示Demo1
下面是github源碼的鏈接:
Github源碼鏈接
3D ViewGroup演示
Camera用于自定義動(dòng)畫
直接上個(gè)代碼實(shí)例,用法和前面的例子沒什么本質(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();//保存當(dāng)前鏡頭狀態(tài)
mCamera.rotateY(mRotateY * interpolatedTime); //使相機(jī)旋轉(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è)置默認(rèn)持續(xù)時(shí)間
setFillAfter(true); //設(shè)置動(dòng)畫結(jié)束后是否保持狀態(tài)
setInterpolator(new LinearInterpolator()); //設(shè)置插值器
centerWidth = width / 2;
centerHeight = height / 2;
}
}
總結(jié)
Camera的使用其實(shí)并不復(fù)雜,只需要記住前面提到的幾個(gè)方法就行。由于Camera最終是輸出一個(gè)矩陣,所以還需要對矩陣有一定的掌握。上面我已經(jīng)給出了矩陣快速使用的指南,大家可以根據(jù)情況自行參考。
如果你覺得還不錯(cuò),那就動(dòng)動(dòng)小捶捶敲個(gè)關(guān)注、點(diǎn)個(gè)贊哦??!