基础框架
package com.example.opengl;
import android.app.Activity;
import android.os.Bundle;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView;
public class MainActivity extends Activity {
GLSurfaceView mView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
mView = new GLSurfaceView(this);
mView.setRenderer(new ClearRenderer());
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
mView.onPause();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
}
}
class ClearRenderer implements GLSurfaceView.Renderer
{
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
// Do nothing special.
}
public void onSurfaceChanged(GL10 gl, int w, int h)
{
gl.glViewport(0, 0, w, h);
}
public void onDrawFrame(GL10 gl)
{
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
}
}
扩展:获取输入事件
package com.example.opengl;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
GL2JNIView mView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
mView = new GL2JNIView(getApplication());
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
mView.onPause();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
}
}
package com.example.opengl;
import android.annotation.SuppressLint;
import android.content.Context;
import android.opengl.GLSurfaceView;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.view.MotionEvent;
class GL2JNIView extends GLSurfaceView {
Renderer mRenderer;
public GL2JNIView(Context context) {
super(context);
//setEGLContextFactory();
//setEGLConfigChooser();
mRenderer = new Renderer();
setRenderer(mRenderer);
}
@SuppressLint("ClickableViewAccessibility")
public boolean onTouchEvent(final MotionEvent event)
{
queueEvent(new Runnable(){
public void run() {
mRenderer.setColor(event.getX() / getWidth(), event.getY() / getHeight(), 1.0f);
}
});
return true;
}
private static class Renderer implements GLSurfaceView.Renderer {
public void onDrawFrame(GL10 gl) {
//GL2JNILib.step();
gl.glClearColor(mRed, mGreen, mBlue, 1.0f);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
//GL2JNILib.init(width, height);
gl.glViewport(0, 0, width, height);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Do nothing.
}
public void setColor(float r, float g, float b){
mRed = r; mGreen = g; mBlue = b;
}
private float mRed;
private float mGreen;
private float mBlue;
}
}