着色器代码
这次准备在 Android 上实现一个带水印的相机预览功能,因此需要两个纹理,一个用于相机预览,一个用于显示水印,顶点着色器如下:
#version 300 es
layout(location=0) in vec4 aPosition;
layout(location=1) in vec4 aCameraTexCoord;
layout(location=2) in vec4 aWatermarkTexCoord;
uniform mat4 mCameraMatrix;
uniform mat4 mWatermarkMatrix;
out vec2 vCameraTexCoord;
out vec2 vWatermarkTexCoord;
void main() {
vCameraTexCoord = (mCameraMatrix * aCameraTexCoord).xy;
vWatermarkTexCoord = (mWatermarkMatrix * aWatermarkTexCoord).xy;
gl_Position = aPosition;
}
片段着色器要注意两个纹理的叠加方式,通过 alpha 值判断即可:
#version 300 es
#extension GL_OES_EGL_image_external_essl3 : require
precision highp float;
uniform samplerExternalOES sCameraTexture;
uniform sampler2D sWatermarkTexture;
in vec2 vCameraTexCoord;
in vec2 vWatermarkTexCoord;
layout(location=0) out vec4 fragColor;
void main() {
vec4 camera = texture(sCameraTexture, vCameraTexCoord);
vec4 watermark = texture(sWatermarkTexture, vWatermarkTexCoord);
// 水印之外的区域显示为相机预览图
float r = watermark.r + (1.0 - watermark.a) * camera.r;
float g = watermark.g + (1.0 - watermark.a) * camera.g;
float b = watermark.b + (1.0 - watermark.a) * camera.b;
fragColor = vec4(r, g, b, 1.0);
}
OpenGL 代码
首先设置顶点坐标、纹理坐标等:
const static GLfloat VERTICES[] = {
-1.0f, -1.0f,
-1.0f, 1.0f,
1.0f, 1.0f,
1.0f, -1.0f
};
const static GLfloat CAMERA_COORDS[] = {
0.0f, 0.0f,
0.0f, 1.0f