(Android) Renderer Example
松和璧
2023-12-01
package com.example.opengltest;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class OpenGLActivity extends Activity implements Renderer {
private GLSurfaceView glsurfaceview;
private static final String TAG = "TEST OPENGL";
private static final int Coordinates_In_A_Vertex = 2;
private static final int Vertices_In_A_Triangle = 3;
private static final int Bits_In_A_Byte = 8;
private static final int Bits_In_A_Float = Float.SIZE;
private static final int Bytes_In_A_Float = Bits_In_A_Float
/ Bits_In_A_Byte;
private FloatBuffer vertices;
private int width;
private int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
glsurfaceview = new GLSurfaceView(this);
glsurfaceview.setRenderer(this);
setContentView(glsurfaceview);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_open_gl, menu);
return true;
}
@Override
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glColor4f(0.64313725490196f, 0.77647058823529f, 0.22352941176471f, 1);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertices);
gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.d(TAG, "Surface Created!");
width = glsurfaceview.getWidth();
height = glsurfaceview.getHeight();
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0, 1, 0, 1, 1, -1);
gl.glClearColor(1, 1, 1, 1);
ByteBuffer byteBuffer = ByteBuffer
.allocateDirect(Coordinates_In_A_Vertex
* Vertices_In_A_Triangle * Bytes_In_A_Float);
byteBuffer.order(ByteOrder.nativeOrder());
vertices = byteBuffer.asFloatBuffer();
vertices.put(new float[] { 0.0f, 0.0f, 0.5f, 1.0f, 1.0f, 0.0f });
vertices.flip();
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
}
}