Unity UI图片实现模糊功能

原理:其实就是获取图片,然后根据偏移获取不同像素,然后根据不同的透明度叠加得出一张模糊图

我这里没有优化正常情况用一个pass就足够

先上个图

拖动材质球Blur Size参数就有如上图效果

下面完整的shader,注意材质球要调渲染层3000就可以使用(PS:移动平台验证过可以使用)

Shader "Effect/ImageBlur"
{
	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
		}
	}
}

下面是工程完整地址

链接:https://pan.baidu.com/s/1SBnNEcqTEzMxHmIxwDSgeA 
提取码:v7q8 

发布了63 篇原创文章 · 获赞 37 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/SnoopyNa2Co3/article/details/98655701