package com.example.tyxiong.myapplication;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.View;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class MainActivity extends Activity {
GLSurfaceView surfaceView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
surfaceView = new GLSurfaceView(this);
final MyRenderer myRenderer = new MyRenderer();
surfaceView.setRenderer(myRenderer);
surfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
setContentView(surfaceView);
surfaceView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
surfaceView.requestRender();
}
});
}
}
class MyRenderer implements GLSurfaceView.Renderer {
float[] rectData = new float[]
{
-2f, 2f, 0f,
2f, 2f, 0f,
-2f, -2f, 0f,
2f, -2f, 0f
};
int[] rectColor = new int[]
{
65535, 0, 0, 0,
0, 65535, 0, 0,
0, 0, 65535, 0,
0, 65535, 65535, 0
};
private float angle=0f;
public FloatBuffer floatUtils(float[] floatArr) {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(floatArr.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
floatBuffer.put(floatArr);
floatBuffer.flip();
return floatBuffer;
}
public IntBuffer intUtils(int[] intArr) {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(intArr.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(intArr);
intBuffer.flip();
return intBuffer;
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glDisable(GL10.GL_DITHER);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0, 0, 0, 0);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glDepthFunc(GL10.GL_LEQUAL);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
float ratio = (float) width / height;
gl.glFrustumf(-ratio, ratio, -1f, 1f, 1f, 10f);
}
@Override
public void onDrawFrame(GL10 gl) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0f,0f,-5f);
gl.glRotatef(angle++,0f,0f,0.1f);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
FloatBuffer pointerData = floatUtils(rectData);
IntBuffer pointColor = intUtils(rectColor);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, pointerData);
gl.glColorPointer(4, GL10.GL_FIXED, 0, pointColor);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
gl.glFinish();
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
}