根据书上教程运行代码报错,2.2的黑屏无效果,4.1的闪退。后研究发现,问题出在在一个物体同时启用了颜色数组和纹理,注释掉
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
运行即可。
核心代码如下
package com.xieyuan.test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.Random;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Intent;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
public class GLRender implements Renderer{
private final static int ONE=0x10000;
//星星总数
private final static int NUM=50;
//存放星星的数组
private Star[] stars=new Star[NUM];
//闪烁的星星
boolean twinkle=true;
//离观察者的距离
float ZOOM=-10f;
//星星的倾角
float tilt=90f;
//闪烁星星的自转
float spin;
private boolean key;
Random random=new Random();
//纹理ID
private int texture;
IntBuffer coord=GLNioUtil.IntBufferUtil(new int[]{
0,0,ONE,0,ONE,ONE,0,ONE
});
IntBuffer vertexs=GLNioUtil.IntBufferUtil(new int[]{
-ONE-ONE,0,
ONE,-ONE,0,
ONE,ONE,0,
-ONE,ONE,0
});
ByteBuffer indices=GLNioUtil.ByteBufferUtil(new byte[]{
1,0,2,3
});
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//启用阴影平滑
gl.glShadeModel(GL10.GL_SMOOTH);
//清除屏幕为黑色背景
gl.glClearColor(0f, 0f, 0f, 0f);
//透视修正
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
//创建纹理
IntBuffer intBuffer=IntBuffer.allocate(1);
gl.glGenTextures(1, intBuffer);
texture=intBuffer.get();
gl.glBindTexture(GL10.GL_TEXTURE_2D, texture);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, GLImage.mBitmap[3], 0);
//启用纹理映射
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glClearColor(0f, 0f, 0f, 0.5f);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
//设置混色函数
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
//启用混色
gl.glEnable(GL10.GL_BLEND);
for(int i=0;i
效果: