首先使用 OpenGL ES 加載原圖进倍,可以參考我的另一篇文章《OpenGL ES 加載圖片并翻轉(zhuǎn)》。頂點著色器代碼不變购对,主要 attribute
屬性傳入頂點坐標和紋理坐標猾昆。
頂點著色器
attribute vec4 Position;
attribute vec2 TextureCoords;
varying vec2 TextureCoordsVarying;
void main()
{
TextureCoordsVarying = TextureCoords;
gl_Position = Position;
}
片元著色器 uniform
傳入紋理圖片,我們將根據(jù)修改紋理坐標的對應關系實現(xiàn)對應的分屏效果骡苞。
片元著色器(原圖)
attribute vec4 Position;
attribute vec2 TextureCoords;
varying vec2 TextureCoordsVarying;
void main()
{
TextureCoordsVarying = TextureCoords;
gl_Position = Position;
}
原圖.png
2分屏
片元著色器(2分屏)
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
void main()
{
vec2 xy = TextureCoordsVarying;
float y;
if (xy.y >= 0.0 && xy.y <= 0.5)
{
y = xy.y + 0.25;
}
else
{
y = xy.y - 0.25;
}
gl_FragColor = texture2D(Texture, vec2(xy.x, y));
}
分屏_2.png
3分屏
片元著色器(3分屏)
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
void main()
{
vec2 xy = TextureCoordsVarying;
if (xy.y < 1.0/3.0)
{
xy.y = xy.y + 1.0/3.0;
}
else if (xy.y > 2.0/3.0)
{
xy.y = xy.y - 1.0/3.0;
}
gl_FragColor = texture2D(Texture, xy);
}
分屏_3.png
4分屏
片元著色器(4分屏)
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
void main()
{
vec2 xy = TextureCoordsVarying;
if (xy.x <= 0.5)
{
xy.x = xy.x * 2.0;
}
else
{
xy.x = (xy.x - 0.5) * 2.0;
}
if (xy.y <= 0.5)
{
xy.y = xy.y * 2.0;
}
else
{
xy.y = (xy.y - 0.5) * 2.0;
}
gl_FragColor = texture2D(Texture, xy);
}
分屏_4.png
6分屏
片元著色器(6分屏)
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
void main()
{
vec2 xy = TextureCoordsVarying;
if (xy.x <= 1.0/3.0)
{
xy.x = xy.x + 1.0/3.0;
}
else if (xy.x >= 2.0/3.0)
{
xy.x = xy.x - 1.0/3.0;
}
if (xy.y <= 1.0/3.0)
{
xy.y = xy.y + 1.0/3.0;
}
else if (xy.y >= 2.0/3.0)
{
xy.y = xy.y - 1.0/3.0;
}
gl_FragColor = texture2D(Texture, xy);
}
分屏_6.png
9分屏
片元著色器(9分屏)
precision highp float;
uniform sampler2D Texture;
varying vec2 TextureCoordsVarying;
void main()
{
vec2 xy = TextureCoordsVarying;
if (xy.x <= 1.0/3.0)
{
xy.x = xy.x * 3.0;
}
else if (xy.x <= 2.0/3.0)
{
xy.x = (xy.x - 1.0/3.0) * 3.0;
}
else
{
xy.x = (xy.x - 2.0/3.0) * 3.0;
}
if (xy.y <= 1.0/3.0)
{
xy.y = xy.y * 3.0;
}
else if (xy.y <= 2.0/3.0)
{
xy.y = (xy.y - 1.0/3.0) * 3.0;
}
else
{
xy.y = (xy.y - 2.0/3.0) * 3.0;
}
gl_FragColor = texture2D(Texture, xy);
}
分屏_9.png