原理:遍历当前像素点周围的部分像素点,累加它们的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)
半径小:
半径大:
|
请发表评论