Android Studio NDK-OpenGL ES封裝SurfaceView

Android Studio NDK-OpenGL ES封裝SurfaceView
Android Studio NDK-OpenGL ES封裝SurfaceView

係『Android OpenGL ES』用『SurfaceView』蒞畀『OpenGL ES』渲染. 之前『SurfaceView』代碼擺係『MainActivity.java』.更佳方法係『SurfaceView』『Runnable』『SurfaceHolder.Callback』封裝成單獨『GameView calss』.以保持代碼『簡潔』同埋『重用』.

  1. 新建『java』
『File->New->Java Class』
  1. 封裝『Runnable』『Callback』
public class GameView extends SurfaceView implements Runnable,SurfaceHolder.Callback{
  1. 『SurfaceView』變量
int view_width,view_height;

public SurfaceHolder surfaceHolder;

public Surface surface;//用蒞渲染

  1. 構造函數
public GameView(Context context) {

super(context);

init(context);// 設置渲染

}

public GameView(Context context, AttributeSet attrs) {

super(context);

init(context);// 設置渲染

}

public GameView(Context context, AttributeSet attrs, int defStyleAttr) {

super(context);

init(context);// 設置渲染

}

  1. 初此渲染设置
public void init(Context context){

this.surfaceHolder = getHolder();

this.surfaceHolder.addCallback(this);

this.surface = surfaceHolder.getSurface();

}

  1. 創建表層,啟動渲染線程 run()
@Override

public void surfaceCreated(SurfaceHolder surfaceHolder){

new Thread(this).start();

}

  1. 表層改變, 當手機方向改變触發, 係游戲要禁止旋轉方向.
 @Override

public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height){

view_width = width;

view_height = height;

}

  1. 表層銷毀
@Override

public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

}

  1. 游戲運算渲染線程
@Override

public void run() {

AssetManager assetManager = getContext().getAssets();

Lib.init(assetManager, surface, view_width, view_height);

while (true) {// 請求渲染

Lib.update();

}

}

 

發表評論