目录
[1. 顶点着色器](#1. 顶点着色器)
[2. 片元着色器](#2. 片元着色器)
[1. 绑定纹理](#1. 绑定纹理)
[2. 绘制纹理](#2. 绘制纹理)
一、获取图片纹理数据
获取图片纹理数据代码如下:
Kotlin
//获取图片1纹理数据
mTextureId = loadTexture(mContext, R.mipmap.scenery)
//获取图片2纹理数据
mTextureMeiNvId = loadTexture(mContext, R.mipmap.meinv)
fun loadTexture(context: Context, resourceId: Int): Int {
var bitmap = generateBitmap(context, resourceId)
if (bitmap == null) {
Log.d(TAG, "resourceId could not be decoded.")
return 0
}
return getImgTexture(bitmap)
}
fun getImgTexture(bitmap: Bitmap): Int {
val textureObjectIds = IntArray(1)
glGenTextures(1, textureObjectIds, 0)
if (textureObjectIds[0] == 0) {
glDeleteTextures(1, textureObjectIds, 0)
return 0
}
glBindTexture(GL_TEXTURE_2D, textureObjectIds[0])
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
texImage2D(GL_TEXTURE_2D, 0, bitmap, 0)
glGenerateMipmap(GL_TEXTURE_2D)
bitmap.recycle()
glBindTexture(GL_TEXTURE_2D, 0)
return textureObjectIds[0]
}
二、着色器编写
1. 顶点着色器
代码如下:
cpp
attribute vec4 a_Position; // 顶点坐标
attribute vec2 a_TextureCoordinates; //纹理坐标
varying vec2 aCoord;
void main(){
gl_Position = a_Position;
aCoord = a_TextureCoordinates;
}
2. 片元着色器
代码如下:
cpp
precision mediump float;// 数据精度
varying vec2 aCoord;
uniform sampler2D u_TextureUnit;
uniform sampler2D u_TextureUnit1;
void main(){
gl_FragColor = mix(texture2D(u_TextureUnit, aCoord), texture2D(u_TextureUnit1, aCoord), 0.5);
}
三、绑定和绘制纹理
1. 绑定纹理
cpp
GLES20.glActiveTexture(GL_TEXTURE0)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureId)
mTextureShaderProgram!!.setUniforms(
mTextureShaderProgram!!.getTextureUniformLocation(),
0
)
GLES20.glActiveTexture(GL_TEXTURE1)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureMeiNvId)
mTextureShaderProgram!!.setUniforms(
mTextureShaderProgram!!.getTextureUniform1Location(),
1
)
2. 绘制纹理
cpp
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 6)
图一:
图二:
叠加后的效果图如下:
四、源码下载
Android OpenGL ES多个纹理实现混叠显示项目源码
下载地址:
https://download.csdn.net/download/github_27263697/90115686
推荐文章