当前位置: 首页 > 科技观察

男孩,是时候创建您的第一个疯狂而酷炫的3D效果了!

时间:2023-03-20 13:17:17 科技观察

背??景介绍Android中有两个Camera类。一个是android.hardware.Camera,用于操作设备的相机。另一个是android.graphics.Camera,可以用来进行3D变换,然后将变换后的矩阵Matrix应用到Canvas等。这个Camera类就是我们本文要介绍的。玩转Camera正如我们之前提到的,Camera是一个可以进行3D变化的类。进行3D变化后,我们可以通过mCamera.getMatrix(Matrix)给变换矩阵Matrix赋值,然后在Canvas上使用。或者,您可以通过mCamera.applyToCanvas(Canvas)直接将转换应用到Canvas。Android中的3D坐标轴Android中的3D坐标轴符合左手坐标系。Camera的默认位置是(0,0,-8)。Camera的Transform操作方法说明getMatrix(mMatrix)给mMatrix赋值。applyToCanvas(mCanvas)将转换后的Matrix直接应用于mCanvas。rotate(x,y,z)旋转。rotateX,rotateY,rotateZ旋转。getLocationX、getLocationY、getLocationZ获取Camera的位置,默认为(0,0,-8)。setLocation(x,y,z)设置相机的位置。translate(x,y,z)平移相机。save()类似于Canvas。restore()类似于Canvas。Camera的方法不多,使用起来比较简单明了。Camera使用示例由于使用Camera的核心是获取经过变换的Matrix,因此需要对Matrix有一定的了解。演示Demo13DViewGroup演示Camera用于自定义动画,直接上传代码示例。用法和前面的例子没有本质区别,都是经过Camera变换得到Matrix矩阵。publicclassCustom3DAnimationextendsAnimation{privateCameramCamera;privateintcenterWidth;privateintcenterHeight;publicvoidsetmRotateY(floatmRotateY){this.mRotateY=mRotateY;}privatefloatmRotateY;publicCustom3DAnimation(){mCamera=newCamera();mRotateY=90;}@OverrideprotectedvoidapplyTransformation(floatinterpolatedTime,Transformationt){Matrixmatrix=t.getMatrix();//获取Transformation的MatrixmCamera.save();//保存当前镜头状态mCamera.rotateY(mRotateY*interpolatedTime);//使相机旋转mCamera.getMatrix(matrix);//应用旋转变换到matrixmCamera.restore();//合并镜头层matrix.preTranslate(centerWidth,centerHeight);//运算前平移matrix.postTranslate(-centerWidth,-centerHeight);//运算后平移}@Overridepublicvoidinitialize(intwidth,intheight,intparentWidth,intparentHeight){super.initialize(width,height,parentWidth,parentHeight);setDuration(5*1000);//设置默认时长setFillAfter(true);//设置是否保持af状态tertheanimationendssetInterpolator(newLinearInterpolator());//设置插值器centerWidth=width/2;centerHeight=height/2;}}总结Camera的使用其实并不复杂,只要记住上面提到的几点即可一种方法就够了。由于Camera最终输出的是矩阵,因此需要对矩阵有一定的把握。上面我已经给出了矩阵的快速使用指南,大家可以根据情况自行参考。