2011年5月23日星期一

創建自定義的 GLSurfaceView,以處理用戶輸入

把前面的"GLSurfaceView 示例"修改, 創建自定義的GLSurfaceView,並實現onTouchEvent()函數, 便可以處理用戶輸入.

本例子中, 用戶在屏幕上移動手指, 畫面顏色會根據而改變.

AndroidGLSurfaceViewActivity.java
package com.AndroidGLSurfaceViewActivity;

import android.app.Activity;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.MotionEvent;

public class AndroidGLSurfaceViewActivity extends Activity {

private MyGLSurfaceView myGLSurfaceView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create our Preview view and set it as the content of our
// Activity
myGLSurfaceView = new MyGLSurfaceView(this);
setContentView(myGLSurfaceView);
}

@Override
protected void onResume() {

super.onResume();
myGLSurfaceView.onResume();
}

@Override
protected void onPause() {

super.onPause();
myGLSurfaceView.onPause();
}

class MyGLSurfaceView extends GLSurfaceView{

MyRenderer myRenderer;

public MyGLSurfaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
myRenderer = new MyRenderer();
setRenderer(myRenderer);
}

@Override
public boolean onTouchEvent(final MotionEvent event) {
// TODO Auto-generated method stub
queueEvent(new Runnable(){

public void run() {
myRenderer.setColor(event.getX()/getWidth(),
event.getY()/getHeight(), 1.0f);
}});
return true;
}
}

}


MyRenderer.java
package com.AndroidGLSurfaceViewActivity;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MyRenderer implements android.opengl.GLSurfaceView.Renderer{

private float red = 0;
private float green = 0;
private float blue = 0;

@Override
public void onDrawFrame(GL10 gl) {
// TODO Auto-generated method stub
gl.glClearColor(red, green, blue, 1.0f);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
}

@Override
public void onSurfaceChanged(GL10 arg0, int arg1, int arg2) {
// TODO Auto-generated method stub

}

@Override
public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) {
// TODO Auto-generated method stub

}

public void setColor(float r, float g, float b){
red = r;
green = g;
blue = b;
}

}


1 則留言: