Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 程式設計:實作圖片 3D 旋轉效果

編輯:關於 Android 程式設計

本文分享一個在 Android 中實作圖片 3D 旋轉效果的實例,供大家參考。

接下來的示例要實作的是圖片的 3D 旋轉效果。

要做 3D 效果一般會想到 OpenGL,但在 Android 平台下其實不必直接動用 OpenGL,而是可以用 Camera 來實現——Camera 底層的原理最終仍是 OpenGL,只是用 Camera 更為方便。Camera 就像一台攝影機,當物體不動時,我們帶著攝影機四處移動,畫面就會產生立體感,能從不同角度觀看同一個物體。廢話不多說,直接看示例。

運行效果如下:

  

 

專案結構:

MainView.java 的程式碼:

 package com.android.graphics; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Camera; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class MainView extends View{ //Camera類 private Camera mCamera; private Bitmap face; private Matrix mMatrix = new Matrix(); private Paint mPaint = new Paint(); private int mLastMotionX, mLastMotionY; //圖片旋轉時的中心點坐標 private int centerX, centerY; //轉動的總距離,跟度數比例1:1 private int deltaX, deltaY; //圖片寬度高度 private int bWidth, bHeight; public MainView(Context context,AttributeSet attributeSet) { super(context,attributeSet); setWillNotDraw(false); mCamera = new Camera(); mPaint.setAntiAlias(true); face = BitmapFactory.decodeResource(getResources(), R.drawable.x); bWidth = face.getWidth(); bHeight = face.getHeight(); centerX = bWidth>>1; centerY = bHeight>>1; } void rotate(int degreeX, int degreeY) { 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 boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: mLastMotionX = x; mLastMotionY = y; break; case MotionEvent.ACTION_MOVE: int dx = x - mLastMotionX; int dy = y - mLastMotionY; rotate(dx, dy); mLastMotionX = x; mLastMotionY = y; break; case MotionEvent.ACTION_UP: break; } return true; } @Override public void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); canvas.drawBitmap(face, mMatrix, mPaint); } } 

main.xml 的程式碼:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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> 

希望本文所述能對大家的 Android 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved