Bootstrap

Android OpenGL ES详解——绘制圆角矩形

1、绘制矩形

代码如下:

renderer类:

package com.example.roundrect

import android.content.Context
import android.opengl.GLES30
import android.opengl.GLSurfaceView.Renderer
import com.opengllib.data.VertexArray
import com.opengllib.programs.ShaderProgram
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class RoundRectRenderer(context: Context) : Renderer {
    private var mVertices = floatArrayOf(
        -0.5f, -0.5f,
        0.5f, 0.5f,
        -0.5f, 0.5f,
        -0.5f, -0.5f,
        0.5f, -0.5f,
        0.5f, 0.5f,
    )
    private var mShaderProgram: ShaderProgram? = null
    private var mContext = context
    private var mVertexArray: VertexArray? = null

    override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
        GLES30.glClearColor(0.6f, 0.7f, 0.8f, 1.0f)
        mVertexArray = VertexArray(mVertices)

        mShaderProgram = ShaderProgram(
            mContext,
            R.raw.roundrect_vertex_shader,
            R.raw.roundrect_fragment_shader
        )
        mShaderProgram?.useProgram()
        mVertexArray?.setVertexAttribPointer(
            0,
            mShaderProgram?.getPositionAttributeLocation()!!,
            2,
            0
        )

    }

    override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
        GLES30.glViewport(0, 0, width, height)
    }

    override fun onDrawFrame(gl: GL10?) {
        GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
        GLES30.glDrawArrays(GLES30.GL_TRIANGLES,0 ,mVertices.size / 2)
    }
}

顶点着色器文件roundrect_vertex_shader.glsl代码如下:

attribute vec4 a_Position;

void main()
{
    gl_Position = a_Position;
}

片元着色器文件roundrect_fragment_shader.glsl代码如下:

precision mediump float;

void main()
{
	gl_FragColor = vec4(0.8, 0.5, 0.3, 1.0);
}

2、绘制圆形

3、绘制圆角矩形

参考文章

使用OpenGL实现圆角效果-腾讯云开发者社区-腾讯云

;