要实现分屏滤镜,首先要使用自定义的着色器加载纹理,至于如何加载纹理,这里不再说明。感兴趣的可以查看之前的一篇文章自定义着色器加载纹理
这篇文章我们只详细说明各个滤镜的着色器文件如何编写
无滤镜
下面是无滤镜的时候,顶点着色器的代码以及片元着色器的代码
顶点着色器
attribute vec4 Position;
attribute vec2 TextureCoords;
varying vec2 TextureCoordsVarying;
void main (void) {
gl_Position = Position;
TextureCoordsVarying = TextureCoords;
}
片元着色器
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
void main (void) {
vec4 mask = texture2D(Texture, TextureCoordsVarying);
gl_FragColor = vec4(mask.rgb, 1.0);
}
下面的所有分屏滤镜,都只需要修改片元着色器,顶点着色器不需要做任何修改,所以接下来的滤镜,不再重复书写顶点着色器
二分屏滤镜
先查看效果,如下图
二分屏
这里实现的二分屏效果是将原图中间的二分之一部分重复显示了两次,舍弃了原图的上面四分之一部分和下面四分之一部分
下面是二分屏滤镜的片元着色器代码:
precision highp float;
uniform sampler2D Texture;
varying highp vec2 TextureCoordsVarying;
void main() {
vec2 uv = TextureCoordsVarying.xy;
float y;
if (uv.y >= 0.0 && uv.y <= 0.5) {
y = uv.y + 0.25;
} else {
y = uv.y - 0.25;
}
gl_FragColor = texture2D(Texture, vec2(uv.x, y));
}
三分屏特效
三分屏这里实现的三分屏特效是将原图的中间三分之一部分重复显示了三次
下面是三分屏特效的片元着色器代码:
precision highp float;
uniform sampler2D Texture;
varying highp vec2 TextureCoordsVarying;
void main() {
vec2 uv = TextureCoordsVarying.xy;
if (uv.y < 1.0/3.0) {
uv.y = uv.y + 1.0/3.0;
} else if (uv.y > 2.0/3.0){
uv.y = uv.y - 1.0/3.0;
}
gl_FragColor = texture2D(Texture, uv);
}
四分屏特效
四分屏因为这里使用的原图是一张宽高相等的正方形图片,所以四分屏特效并不需要裁剪原图片,只是将原图缩小到原图的四分之一
precision highp float;
uniform sampler2D Texture;
varying highp vec2 TextureCoordsVarying;
void main() {
vec2 uv = TextureCoordsVarying.xy;
if(uv.x <= 0.5){
uv.x = uv.x * 2.0;
}else{
uv.x = (uv.x - 0.5) * 2.0;
}
if (uv.y<= 0.5) {
uv.y = uv.y * 2.0;
}else{
uv.y = (uv.y - 0.5) * 2.0;
}
gl_FragColor = texture2D(Texture, uv);
}
六分屏特效
六分屏precision highp float;
uniform sampler2D Texture;
varying highp vec2 TextureCoordsVarying;
void main() {
vec2 uv = TextureCoordsVarying.xy;
if(uv.x <= 1.0 / 3.0){
uv.x = uv.x + 1.0/3.0;
}else if(uv.x >= 2.0/3.0){
uv.x = uv.x - 1.0/3.0;
}
if(uv.y <= 0.5){
uv.y = uv.y + 0.25;
}else {
uv.y = uv.y - 0.25;
}
gl_FragColor = texture2D(Texture, uv);
}
九分屏特效
九分屏precision highp float;
uniform sampler2D Texture;
varying highp vec2 TextureCoordsVarying;
void main() {
vec2 uv = TextureCoordsVarying.xy;
if (uv.x < 1.0 / 3.0) {
uv.x = uv.x * 3.0;
} else if (uv.x < 2.0 / 3.0) {
uv.x = (uv.x - 1.0 / 3.0) * 3.0;
} else {
uv.x = (uv.x - 2.0 / 3.0) * 3.0;
}
if (uv.y <= 1.0 / 3.0) {
uv.y = uv.y * 3.0;
} else if (uv.y < 2.0 / 3.0) {
uv.y = (uv.y - 1.0 / 3.0) * 3.0;
} else {
uv.y = (uv.y - 2.0 / 3.0) * 3.0;
}
gl_FragColor = texture2D(Texture, uv);
}
网友评论