Android OpenGL ES 2.0入门学习 1

从今天我开始学习Android OpenGL ES 2.0,写下博客作为记录。

首先创建一个空白的项目;

主界面MainActivity.java代码:

import android.app.Activity;
import android.app.ActivityManager;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {
    private GLSurfaceView glSurfaceView;//初始化
    private boolean rendererSet=false;//是否处在有效状态

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        glSurfaceView=new GLSurfaceView(this);
        //检查系统是否支持OpenGL ES 2.0
        ActivityManager activityManager= (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ConfigurationInfo configurationInfo=activityManager.getDeviceConfigurationInfo();
        boolean supportses2=configurationInfo.reqGlEsVersion>=20000;
        if(supportses2){
            glSurfaceView.setEGLContextClientVersion(2);
            glSurfaceView.setRenderer(new FirstOpenRenderer());
            rendererSet=true;
        }else {
            Toast.makeText(this,"This device does not support OpenGL ES 2.0",Toast.LENGTH_LONG).show();
            return;
        }
        setContentView(glSurfaceView);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(rendererSet){
            glSurfaceView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(rendererSet){
            glSurfaceView.onResume();
        }
    }
}
类 FirstOpenRendererd.java代码:

import android.opengl.GLSurfaceView;
import static android.opengl.GLES20.GL_COLOR_BUFFER_BIT;
import static android.opengl.GLES20.glClear;
import static android.opengl.GLES20.glClearColor;
import static android.opengl.GLES20.glViewport;

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

/**
 * Created by Administrator on 2017/2/16.
 */

public class FirstOpenRenderer implements GLSurfaceView.Renderer{
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        glClearColor(1.0f,0.0f,0.0f,0.0f);
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        glViewport(0,0,width,height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        glClear(GL_COLOR_BUFFER_BIT);
    }
}
代码运行结果:会看到空白的红色屏幕。

写博客主要是为了自己学习记录,书籍《OpenGL ES 应用开发实践指南》中有详细介绍。



你可能感兴趣的:(Android)