OpenGLES版Helloworld(Android平台)

        对于开发人员来说,学习一门新技术的第一个demo,一般都是helloworld。

        因此本文主要也是在Android平台上阐述如何基于openGL ES开发一个最简单的渲染程序。关于openGL ES相关概念,可以参考前面一篇文章:OpenGL ES简介及几个相关重要概念

一、基本步骤

        在安卓上开发最简单的OpenGL程序,最简单的步骤就只要3步:

1、定义MyGLSurfaceView继承GLSurfaceView;

2、实现接口GLSurfaceView.Renderer;

3、布局中引用;

二、开发Helloworld程序

1、定义MyGLSurfaceView继承GLSurfaceView

        如下自定义一个MyGLSurfaceView类,并在里面调用GLSurfaceView的setRenderer方法。绑定渲染实现。

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;

public class MyGLSurfaceView extends GLSurfaceView {
    public MyGLSurfaceView(Context context) {
        super(context);
    }

    public MyGLSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //1.自定义的 Render,在 Render中实现绘制
        MyGLRender myGlRender = new MyGLRender();
        //2.调用 GLSurfaceView的setRenderer方法
        setRenderer(myGlRender);
    }
}

2、实现接口GLSurfaceView.Renderer

        自定义一个Render,实现GLSurfaceView.Renderer接口。

        其中,在onSurfaceChanged中改变宽高大小,没什么特殊需求的话就是固定写法。然后在onDrawFrame去进行相关绘制。代码如下:

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;

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

public class MyGLRender implements GLSurfaceView.Renderer {


    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

    }

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

    @Override
    public void onDrawFrame(GL10 gl) {
        //使用蓝色清屏
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        GLES20.glClearColor(0f,0f,1f,1f);
    }
}

        在这个简单的例子中,我们的绘制内容就是简单地将整个屏幕渲染成蓝色。

3、布局中引入

        最后,在布局中引用自定义的GLSurfaceView,如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.opengl_helloworld.MyGLSurfaceView
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

4、运行效果

        最后看一下运行的效果如下:

        该demo已放到github上,有需要的可以下载看看:

https://github.com/weekend-y/openGL_Android_demo/tree/master/OpenGL_Helloworld

猜你喜欢

转载自blog.csdn.net/weekend_y45/article/details/126000415
今日推荐