Android实现3D旋转效果
16lz
2021-01-24
下面的示例是在Android中实现图片3D旋转的效果。
实现3D效果一般使用OpenGL,但在Android平台下可以不直接使用OpenGL,而是使用Camera实现,Camera中原理最终还是使用OpenGL,不过使用Camera比较方便。Camera类似一个摄像机,当物体不动时,我们带着摄像机四处移动,在摄像机里面的画面就会有立体感,就可以从其它的角度观看这个物体。废话不多说,直接看示例。
运行效果如下:
项目结构:
MainView.java中代码:
packagecom.android.graphics;importandroid.content.Context;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.graphics.Camera;
importandroid.graphics.Canvas;
importandroid.graphics.Matrix;
importandroid.graphics.Paint;
importandroid.util.AttributeSet;
importandroid.view.MotionEvent;
importandroid.view.View;
public classMainView extendsView{
// Camera类
privateCameramCamera;
privateBitmapface;
privateMatrixmMatrix= newMatrix();
privatePaintmPaint= newPaint();
private intmLastMotionX,mLastMotionY;
// 图片旋转时的中心点坐标
private intcenterX,centerY;
// 转动的总距离,跟度数比例1:1
private intdeltaX,deltaY;
// 图片宽度高度
private intbWidth,bHeight;
publicMainView(Contextcontext,AttributeSetattributeSet){
super(context,attributeSet);
setWillNotDraw( false);
mCamera= newCamera();
mPaint.setAntiAlias( true);
face=BitmapFactory.decodeResource(getResources(),R.drawable.x);
bWidth=face.getWidth();
bHeight=face.getHeight();
centerX=bWidth>>1;
centerY=bHeight>>1;
}
voidrotate( intdegreeX, intdegreeY){
deltaX+=degreeX;
deltaY+=degreeY;
mCamera.save();
mCamera.rotateY(deltaX);
mCamera.rotateX(-deltaY);
mCamera.translate(0,0,-centerX);
mCamera.getMatrix(mMatrix);
mCamera.restore();
// 以图片的中心点为旋转中心,如果不加这两句,就是以(0,0)点为旋转中心
mMatrix.preTranslate(-centerX,-centerY);
mMatrix.postTranslate(centerX,centerY);
mCamera.save();
postInvalidate();
}
@Override
public booleanonTouchEvent(MotionEventevent){
intx=( int)event.getX();
inty=( int)event.getY();
switch(event.getAction()){
caseMotionEvent.ACTION_DOWN:
mLastMotionX=x;
mLastMotionY=y;
break;
caseMotionEvent.ACTION_MOVE:
intdx=x-mLastMotionX;
intdy=y-mLastMotionY;
rotate(dx,dy);
mLastMotionX=x;
mLastMotionY=y;
break;
caseMotionEvent.ACTION_UP:
break;
}
return true;
}
@Override
public voiddispatchDraw(Canvascanvas){
super.dispatchDraw(canvas);
canvas.drawBitmap(face,mMatrix,mPaint);
}
}
main.xml中代码:
<? xmlversion="1.0"encoding="utf-8" ?>< LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"
android:orientation ="vertical"
android:layout_width ="fill_parent"
android:layout_height ="fill_parent"
>
< com.android.graphics.MainView
android:id ="@+id/cv"
android:layout_width ="fill_parent"
android:layout_height ="wrap_content"
/>
</LinearLayout>
最后,希望转载的朋友能够尊重作者的劳动成果,加上转载地址:http://www.cnblogs.com/hanyonglu/archive/2012/02/12/2347636.html谢谢。
完毕。^_^
更多相关文章
- Android——SpannableString字体大小不一致垂直居中
- Android(安卓)ViewFlipper触摸动画
- Eclipse Android项目导入Android(安卓)Studio时常见的编译错误及
- ImageView的属性 android:scaleType
- Android(安卓)selector背景选择器的使用详解
- 玩转Android---2D图形及动画---图片处理
- Android瀑布流照片墙、滑动切换图片
- Android(安卓)Gallery控件使用方法详解
- android课后作业