Shader:
Shader "VT131A/GaussianBlur"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
_StencilComp("Stencil Comparison", Float) = 8
_Stencil("Stencil ID", Float) = 0
_StencilOp("Stencil Operation", Float) = 0
_StencilWriteMask("Stencil Write Mask", Float) = 255
_StencilReadMask("Stencil Read Mask", Float) = 255
_ColorMask("Color Mask", Float) = 15
_BlurSize("Blur Size", Float) = 2
}
CGINCLUDE
#include "UnityCG.cginc"
sampler2D _MainTex;
uniform half4 _MainTex_TexelSize;
uniform float _BlurSize;
static const half weight[4] = { 0.0205, 0.0855, 0.232, 0.324 };
static const half4 coordOffset = half4(1.0h, 1.0h, -1.0h, -1.0h);
struct v2f_blurSGX
{
float4 pos:SV_POSITION;
half2 uv:TEXCOORD0;
half4 blurFactor:TEXCOORD1;
};
v2f_blurSGX vert_BlurHorizontal(appdata_img v)
{
v2f_blurSGX o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.texcoord.xy;
o.blurFactor.xy = _MainTex_TexelSize.xy * 2 * _BlurSize;
return o;
}
fixed4 Tex2DBlurring(sampler2D tex, half2 texcood, half2 blur)
{
//快速模糊
//const int KERNEL_SIZE = 3;
//const float KERNEL_[3] = { 0.4566, 1.0, 0.4566 };
//中等模糊
//const int KERNEL_SIZE = 5;
//const float KERNEL_[5] = { 0.2486, 0.7046, 1.0, 0.7046, 0.2486 };
//高级模糊
const int KERNEL_SIZE = 7;
const float KERNEL_[7] = { 0.1719, 0.4566, 0.8204, 1.0, 0.8204, 0.4566, 0.1719 };
float4 o = 0;
float sum = 0;
float2 shift = 0;
for (int x = 0; x < KERNEL_SIZE; x++)
{
shift.x = blur.x * (float(x) - KERNEL_SIZE / 2);
for (int y = 0; y < KERNEL_SIZE; y++)
{
shift.y = blur.y * (float(y) - KERNEL_SIZE / 2);
float2 uv = texcood + shift;
float weight = KERNEL_[x] * KERNEL_[y];
sum += weight;
o += tex2D(tex, uv) * weight;
}
}
return o / sum;
}
fixed4 frag_Blur(v2f_blurSGX i) :SV_Target
{
return Tex2DBlurring(_MainTex,i.uv,i.blurFactor.xy);
}
ENDCG
SubShader
{
// No culling or depth
Cull Off ZWrite Off
Stencil
{
Ref[_Stencil]
Comp[_StencilComp]
Pass[_StencilOp]
ReadMask[_StencilReadMask]
WriteMask[_StencilWriteMask]
}
Fog{ Mode Off }
Blend SrcAlpha OneMinusSrcAlpha
ColorMask[_ColorMask]
Pass
{
CGPROGRAM
#pragma vertex vert_BlurHorizontal
#pragma fragment frag_Blur
ENDCG
}
}
}
实列:
public Sequence doGBlurSeq;
public void DoGaussianBlurAni()
{
doGBlurSeq = DOTween.Sequence();
doGBlurSeq.Append(
DOTween.To(() => blurSize, x => blurSize = x, -3, 3).OnComplete(() =>
{
//模糊的时候执行的事件
})
)
.Append(DOTween.To(() => blurSize, x => blurSize = x, 0, 3))
.SetLoops(-1)
.SetEase(Ease.Linear)
.OnUpdate(() =>
{
feature.GetComponent<Image>().material.SetFloat("_BlurSize", blurSize);
})
;
}