原理:遍歷當前像素點周圍的部分像素點,累加它們的rgba,根據距離設置權重並相乘,最後再根據總權重獲取該總和的平均值,將該平均值設置爲當前像素點的顏色。
local vert = [[
attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;
#ifdef GL_ES
varying lowp vec4 v_fragmentColor;
varying mediump vec2 v_texCoord;
#else
varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
#endif
void main()
{
gl_Position = CC_PMatrix * a_position;
v_fragmentColor = a_color;
v_texCoord = a_texCoord;
}
]]
local frag = [[
#ifdef GL_ES
precision mediump float;
#endif
varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
uniform float limit; // 半徑
uniform vec2 my_size; // 紋理大小(寬和高),爲了計算周圍各點的紋理座標,必須傳入它,因爲紋理座標範圍是0~1
void main(void)
{
vec2 unit = 1.0 / my_size.xy; // 單位尺寸
float r = limit;
float step = r / 2.0; // 步長
float totalWeight = 0.0; // 總權重
vec4 all = vec4(0); // 所有像素點顏色之和
// 遍歷當前像素點周圍的所有像素點,將它們的顏色值相加
// 根據像素點距離當前像素點的距離設置權重
for(float i = -r; i < r; i += step)
{
for(float j = -r; j < r; j += step)
{
// 權重
float weight = (r - abs(i)) * (r - abs(j));
// 加上該像素點顏色值*權重
all += texture2D(CC_Texture0, v_texCoord + vec2(i * unit.x, j * unit.y)) * weight;
totalWeight += weight;
}
}
// 設置當前像素點的顏色爲總顏色之和除以總權重
gl_FragColor = all / totalWeight;
}
]]
-- 1.創建glProgram
local glProgram = cc.GLProgram:createWithByteArrays(vert, frag)
-- 2.獲取glProgramState
local glProgramState = cc.GLProgramState:getOrCreateWithGLProgram(glProgram)
-- 3.設置屬性值
glProgramState:setUniformFloat("limit", 10)
-- 4.獲取材質的尺寸。self.blur爲Sprite
local size = self.blur:getTexture():getContentSizeInPixels()
glProgramState:setUniformVec2("my_size", cc.p(size.width, size.height))
self.blur:setGLProgram(glProgram)
self.blur:setGLProgramState(glProgramState)
半徑小:
半徑大: