經過修改Swift+OpenGLES 展現圖片中的片元着色器代碼,實現對圖片的修改完成一些簡單濾鏡效果。算法
經過對色值修改,而後使圖片呈現灰度,對色值修改方案基本以下:bash
對片元着色器修改代碼以下:post
precision highp float;
varying lowp vec2 varyTextCoord;
uniform sampler2D colorMap;
vec3 W = vec3(0.2125,0.7154,0.0721);
void main() {
vec4 color = texture2D(colorMap, varyTextCoord);
float gray = dot(color.rgb,W);
gl_FragColor = vec4(vec3(gray),color.a);
}
複製代碼
片元着色器修改代碼以下:ui
precision highp float;
varying lowp vec2 varyTextCoord;
uniform sampler2D colorMap;
void main() {
vec4 color = texture2D(colorMap, vec2(varyTextCoord.x,1.0 - varyTextCoord.y));
gl_FragColor = color;
}
複製代碼
片元着色器修改代碼以下,每行都作了詳細註釋:spa
precision highp float;
//旋轉角度
const float uD = 60.0;
//旋轉半徑比例
const float uR = 0.6;
varying lowp vec2 varyTextCoord;
uniform sampler2D colorMap;
void main() {
//紋理圖片相對大小
ivec2 ires = ivec2(1,1);
//相對直徑
float Res = float(ires.y);
vec2 st = varyTextCoord;
//旋轉半徑
float Radius = Res * uR;
//紋理相對座標
vec2 xy = Res * st;
//以圖片中心點爲旋轉中心,求與半徑向量差目的是爲了獲得:1.長度是否在旋轉範圍內,2.角度加上旋轉角度
vec2 dxy = xy - Res/2.0;
//長度
float r = length(dxy);
//拋物線遞減因子
float attenValue = (1.0 - (r/Radius) * (r/Radius));
//旋轉角度
float beta = atan(dxy.y,dxy.x) + radians(uD) * 2.0 *attenValue;
//在旋轉範圍內進行旋轉、而後加上半徑向量恢復到紋理相對座標
if(r <= Radius) {
xy = Res/2.0 + r*vec2(cos(beta),sin(beta));
}
//從新拿到紋理座標
st = xy/Res;
gl_FragColor = texture2D(colorMap,st);
}
複製代碼
其中vec2 dxy = xy - Res/2.0;
的目的已作註釋,爲更清晰理解見下圖:code
片元着色器修改代碼以下:orm
precision mediump float;
varying vec2 varyTextCoord;
uniform sampler2D colorMap;
//自定義圖片大小,用於分割
const vec2 TexSize = vec2(500,500);
//分割大小即馬賽克大小
const vec2 mosaicSize = vec2(20.0,20.0);
void main() {
vec2 textCoSize = vec2(varyTextCoord.x * TexSize.x, varyTextCoord.y * TexSize.y);
vec2 mosaicTex = vec2(floor(textCoSize.x/mosaicSize.x) *mosaicSize.x , floor(textCoSize.y/mosaicSize.y) * mosaicSize.y);
vec2 textC = vec2(mosaicTex.x / TexSize.x, mosaicTex.y / TexSize.y);
gl_FragColor = texture2D(colorMap,textC);
}
複製代碼