編輯:關於 Android 程式設計
本文示範如何用 OpenGL ES 2.0 畫出一顆可以用手指旋轉的球體,並附上完整的四個核心類別。
package test.com.opengles6_1;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.opengl.GLES20;
import android.os.Build;
@SuppressLint("NewApi")
public class Ball {
int mProgram; // 自訂渲染管線著色器程式 id
int muMVPMatrixHandle; // 總變換矩陣引用
int maPositionHandle; // 頂點位置屬性引用
int muRHandle; // 球半徑屬性引用
String mVertexShader; // 頂點著色器
String mFragmentShader; // 片元著色器
FloatBuffer mVertexBuffer; // 頂點座標資料緩衝
int vCount = 0;
float yAngle = 0; // 繞 y 軸旋轉角度
float xAngle = 0; // 繞 x 軸旋轉角度
float zAngle = 0; // 繞 z 軸旋轉角度
float r = 0.8f;
public Ball(MySurfaceView mv) {
initVertexData(); // 初始化頂點座標
initShader(mv); // 初始化 shader
}
// 初始化頂點座標資料
public void initVertexData() {
ArrayList<Float> alVertix = new ArrayList<>(); // 存放頂點座標
final int angleSpan = 2; // 球體切分的角度粒度
for (int vAngle = -90; vAngle < 90; vAngle = vAngle + angleSpan) { // 垂直方向
for (int hAngle = 0; hAngle <= 360; hAngle = hAngle + angleSpan) { // 水平方向
float x0 = (float) (r * Constant.UNIT_SIZE * Math.cos(Math.toRadians(vAngle)) * Math.cos(Math.toRadians(hAngle)));
float y0 = (float) (r * Constant.UNIT_SIZE * Math.cos(Math.toRadians(vAngle)) * Math.sin(Math.toRadians(hAngle)));
float z0 = (float) (r * Constant.UNIT_SIZE * Math.sin(Math.toRadians(vAngle)));
float x1 = (float) (r * Constant.UNIT_SIZE * Math.cos(Math.toRadians(vAngle)) * Math.cos(Math.toRadians(hAngle + angleSpan)));
float y1 = (float) (r * Constant.UNIT_SIZE * Math.cos(Math.toRadians(vAngle)) * Math.sin(Math.toRadians(hAngle + angleSpan)));
float z1 = (float) (r * Constant.UNIT_SIZE * Math.sin(Math.toRadians(vAngle)));
float x2 = (float) (r * Constant.UNIT_SIZE * Math.cos(Math.toRadians(vAngle + angleSpan)) * Math.cos(Math.toRadians(hAngle + angleSpan)));
float y2 = (float) (r * Constant.UNIT_SIZE * Math.cos(Math.toRadians(vAngle + angleSpan)) * Math.sin(Math.toRadians(hAngle + angleSpan)));
float z2 = (float) (r * Constant.UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)));
float x3 = (float) (r * Constant.UNIT_SIZE * Math.cos(Math.toRadians(vAngle + angleSpan)) * Math.cos(Math.toRadians(hAngle)));
float y3 = (float) (r * Constant.UNIT_SIZE * Math.cos(Math.toRadians(vAngle + angleSpan)) * Math.sin(Math.toRadians(hAngle)));
float z3 = (float) (r * Constant.UNIT_SIZE * Math.sin(Math.toRadians(vAngle + angleSpan)));
// 兩個三角形構成一個四邊形,也就是兩條經線與兩條緯線相交圍成的區域
alVertix.add(x1); alVertix.add(y1); alVertix.add(z1);
alVertix.add(x3); alVertix.add(y3); alVertix.add(z3);
alVertix.add(x0); alVertix.add(y0); alVertix.add(z0);
alVertix.add(x1); alVertix.add(y1); alVertix.add(z1);
alVertix.add(x2); alVertix.add(y2); alVertix.add(z2);
alVertix.add(x3); alVertix.add(y3); alVertix.add(z3);
}
}
// 頂點數量為座標值數量的 1/3,因為一個頂點有三個座標
vCount = alVertix.size() / 3;
float vertices[] = new float[vCount * 3];
for (int i = 0; i < alVertix.size(); i++) {
vertices[i] = alVertix.get(i);
}
// 建立頂點座標資料緩衝,每個 float 佔 4 個位元組
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder()); // 設定位元組順序
mVertexBuffer = vbb.asFloatBuffer();
mVertexBuffer.put(vertices);
mVertexBuffer.position(0);
// 特別提醒:不同平台的位元組順序不同,非位元組單位的資料一定要經過 ByteBuffer 轉換,
// 關鍵是必須用 ByteOrder 設定 nativeOrder(),否則可能出問題
}
// 初始化 shader
public void initShader(MySurfaceView mv) {
mVertexShader = ShaderUtil.loadFromAssetsFile("vertex.sh", mv.getResources());
mFragmentShader = ShaderUtil.loadFromAssetsFile("frag.sh", mv.getResources());
mProgram = ShaderUtil.createProgram(mVertexShader, mFragmentShader);
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
muRHandle = GLES20.glGetUniformLocation(mProgram, "uR");
}
@TargetApi(Build.VERSION_CODES.FROYO)
@SuppressLint("NewApi")
public void drawSelf() {
MatrixState.rotate(xAngle, 1, 0, 0); // 繞 X 軸旋轉
MatrixState.rotate(yAngle, 0, 1, 0); // 繞 Y 軸旋轉
MatrixState.rotate(zAngle, 0, 0, 1); // 繞 Z 軸旋轉
GLES20.glUseProgram(mProgram); // 指定使用的 shader 程式
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
GLES20.glUniform1f(muRHandle, r * Constant.UNIT_SIZE); // 傳入半徑
GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, 3 * 4, mVertexBuffer);
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vCount); // 繪製球體
}
}
package test.com.opengles6_1;
import java.nio.ByteBuffer;
import android.opengl.Matrix;
// 儲存系統矩陣狀態的類別
public class MatrixState {
private static float[] mProjMatrix = new float[16]; // 4x4 投影矩陣
private static float[] mVMatrix = new float[16]; // 攝影機位置朝向矩陣
private static float[] currMatrix; // 目前變換矩陣
// 保護變換矩陣的堆疊
static float[][] mStack = new float[10][16];
static int stackTop = -1;
public static void setInitStack() { // 取得初始不變換矩陣
currMatrix = new float[16];
Matrix.setRotateM(currMatrix, 0, 0, 1, 0, 0);
}
public static void pushMatrix() { // 保護目前矩陣
stackTop++;
for (int i = 0; i < 16; i++) {
mStack[stackTop][i] = currMatrix[i];
}
}
public static void popMatrix() { // 恢復矩陣
for (int i = 0; i < 16; i++) {
currMatrix[i] = mStack[stackTop][i];
}
stackTop--;
}
public static void translate(float x, float y, float z) { // 平移
Matrix.translateM(currMatrix, 0, x, y, z);
}
public static void rotate(float angle, float x, float y, float z) { // 旋轉
Matrix.rotateM(currMatrix, 0, angle, x, y, z);
}
// 設定攝影機
static ByteBuffer llbb = ByteBuffer.allocateDirect(3 * 4);
static float[] cameraLocation = new float[3];
public static void setCamera(float cx, float cy, float cz, // 攝影機位置
float tx, float ty, float tz, // 目標點
float upx, float upy, float upz) { // UP 向量
Matrix.setLookAtM(mVMatrix, 0, cx, cy, cz, tx, ty, tz, upx, upy, upz);
}
// 設定透視投影參數
public static void setProjectFrustum(float left, float right, float bottom,
float top, float near, float far) {
Matrix.frustumM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
// 設定正交投影參數
public static void setProjectOrtho(float left, float right, float bottom,
float top, float near, float far) {
Matrix.orthoM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
// 取得物體的總變換矩陣
static float[] mMVPMatrix = new float[16];
public static float[] getFinalMatrix() {
Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, currMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
return mMVPMatrix;
}
// 取得物體自身的變換矩陣
public static float[] getMMatrix() {
return currMatrix;
}
}
package test.com.opengles6_1;
import android.content.Context;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.EGLConfig;
class MySurfaceView extends GLSurfaceView {
private final float TOUCH_SCALE_FACTOR = 180.0f / 320; // 角度縮放比例
private SceneRenderer mRenderer; // 場景渲染器
Ball ball; // 球
private float mPreviousY; // 上次觸控 Y 座標
private float mPreviousX; // 上次觸控 X 座標
public MySurfaceView(Context context) {
super(context);
this.setEGLContextClientVersion(2); // 使用 OpenGL ES 2.0
mRenderer = new SceneRenderer();
setRenderer(mRenderer);
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); // 主動渲染
}
@Override
public boolean onTouchEvent(MotionEvent e) {
float y = e.getY();
float x = e.getX();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
float dy = y - mPreviousY; // Y 位移
float dx = x - mPreviousX; // X 位移
ball.yAngle += dx * TOUCH_SCALE_FACTOR;
ball.xAngle += dy * TOUCH_SCALE_FACTOR;
}
mPreviousY = y;
mPreviousX = x;
return true;
}
private class SceneRenderer implements GLSurfaceView.Renderer {
public void onDrawFrame(GL10 gl) {
// 清除深度緩衝與顏色緩衝
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
MatrixState.pushMatrix(); // 保護現場
MatrixState.pushMatrix();
ball.drawSelf();
MatrixState.popMatrix(); // 恢復現場
MatrixState.popMatrix();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glViewport(0, 0, width, height);
Constant.ratio = (float) width / height;
// 依寬高比產生透視投影矩陣
MatrixState.setProjectFrustum(-Constant.ratio, Constant.ratio, -1, 1, 20, 100);
// 產生攝影機 9 參數位置矩陣
MatrixState.setCamera(0, 0, 30, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
MatrixState.setInitStack();
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
GLES20.glClearColor(0f, 0f, 0f, 1.0f); // 背景色
ball = new Ball(MySurfaceView.this);
GLES20.glEnable(GLES20.GL_DEPTH_TEST); // 開啟深度檢測
GLES20.glEnable(GLES20.GL_CULL_FACE); // 開啟背面剪裁
}
}
}
package test.com.opengles6_1;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import android.content.res.Resources;
import android.opengl.GLES20;
import android.util.Log;
// 載入頂點 Shader 與片元 Shader 的工具類別
public class ShaderUtil {
// 載入指定 shader
public static int loadShader(int shaderType, String source) {
int shader = GLES20.glCreateShader(shaderType);
if (shader != 0) {
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
int[] compiled = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) { // 編譯失敗,印出錯誤並刪除
Log.e("ES20_ERROR", "Could not compile shader " + shaderType + ":");
Log.e("ES20_ERROR", GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
// 建立 shader 程式
public static int createProgram(String vertexSource, String fragmentSource) {
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0) {
return 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0) {
return 0;
}
int program = GLES20.glCreateProgram();
if (program != 0) {
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e("ES20_ERROR", "Could not link program: ");
Log.e("ES20_ERROR", GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
}
return program;
}
// 檢查每一步是否有錯誤
public static void checkGlError(String op) {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
Log.e("ES20_ERROR", op + ": glError " + error);
throw new RuntimeException(op + ": glError " + error);
}
}
// 從 assets 的 sh 腳本載入 shader 內容
public static String loadFromAssetsFile(String fname, Resources r) {
String result = null;
try {
InputStream in = r.getAssets().open(fname);
int ch = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((ch = in.read()) != -1) {
baos.write(ch);
}
byte[] buff = baos.toByteArray();
baos.close();
in.close();
result = new String(buff, "UTF-8");
result = result.replaceAll("\r\n", "\n");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
效果圖:

幾個實作時容易忽略的細節:球體是以「經緯度切分 + 兩個三角形拼一個四邊形」的方式生成頂點,angleSpan 越小球越圓滑但頂點數量也越多;顶点座標一定要經過 ByteBuffer 並設定 nativeOrder(),否則跨平台時容易出現顯示異常;而觸控旋轉之所以順滑,靠的是 onTouchEvent 中把位移乘上縮放係數累加到 xAngle、yAngle,再在 drawSelf() 裡轉換成旋轉矩陣。
微信支付開發(七):刷卡支付(Micropay)API 與 PHP 類封裝實作
本文說明微信支付中「刷卡支付」的接入流程。所謂刷卡支付,是指使用者打開微信錢包的付款碼畫面,由商戶端的掃碼設備讀取條碼或二維碼後提交,完成整個支付過程——也就是交易的主動
Android 實現畫板/寫字板功能(附源碼下載)
本文分享一個用 Android 實現簡單寫字板的完整示例。原理並不複雜:把一張圖片解碼成可變的 Bitmap 副本,關聯到 Canvas 上,然後根據手指的移動軌跡不斷畫
Android ContentProvider 組件數據共享解析
ContentProvider 主要用於對外共享數據。它以自己的方式組織數據,並對外提供增刪改查接口。其他應用可透過 ContentResolver 訪問指定 URI 對
Android 入門:用 ActivityGroup 加 GridView 打造 Tab 分頁
做 Android 客戶端或瀏覽器類應用時,Tab 分頁幾乎是標配,用來搭建整體的介面骨架。說到 Tab,很多人第一時間會想到 TabHost 與 TabActivity