Unity UI图片实现模糊功能

8 篇文章 0 订阅

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

我这里没有优化正常情况用一个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 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值