Unity Shader : 模糊(blur)与透明(transparent)效果实例

在日常开发中有些情况下需要模糊和透明像素来达到效果,怎么实现呢,其实并不难

模糊的实现原理是当前像素的颜色改为周围像素的颜色的平均值,距离当前像素越远的权重越低,这样效果比较好。

透明可以通过alpha混合实现,但是注意需关闭深度缓冲区,且渲染队列(Queue)和渲染标签(RenderType)设为为Transparent

下面为一个简单实例:

UnityShaderDemo

Shader "Unlit/Test_15"
{
	Properties
	{
	
		_BlurTex("BlurTex",2D) = "white" {}
		_Color("Color",Color) = (1,1,1,1)
		_Radius("Radius",Range(0,10)) = 1
		_Trans("Trans",Range(0,1)) = 1
		_BlurIntensity("BlurIntensity",Range(0,10)) = 3
	}
	SubShader
	{
			Tags { "Queue" = "Transparent" "RenderType" = "Transparent" } //切换为transparent透明渲染队列
			LOD 100

			ZWrite off  //透明效果不需要写入深度缓冲区
			Blend SrcAlpha OneMinusSrcAlpha  //alpha混合

		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			
			#include "UnityCG.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
				float4 color : COLOR;
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				float4 vertex : SV_POSITION;
				float4 color : COLOR;
			};

			
			sampler2D _BlurTex;//需要模糊的贴图
			float _Radius;//需要模糊的半径
			float4 _BlurTex_TexelSize;//贴图的像素大小
			float _Trans;//透明的程度
			float _BlurIntensity;//需要模糊的程度
			

			fixed4 Blur(sampler2D tex, half2 uv, half2 blurSize) //计算模糊的函数方法,tex为需要模糊的图像,uv为需要模糊图像的uv坐标,blurSize为需要取周围像素的范围
			{
				int KERNEL_SIZE = _BlurIntensity;
				float4 o = 0;
				float sum = 0;
				float weight;
				half2 texcoord;
				for (int x = -KERNEL_SIZE / 2; x <= KERNEL_SIZE / 2; x++) 
				{
					for (int y = -KERNEL_SIZE / 2; y <= KERNEL_SIZE / 2; y++) 
					{
						texcoord = uv;
						texcoord.x += blurSize.x*x;
						texcoord.y += blurSize.y*y;
						weight = 1.0 / (abs(x) + abs(y) + 2);
						o += tex2D(tex, texcoord)*weight;
						sum += weight;
					}
				}
				return o / sum;
			}

			
			v2f vert (appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.color = v.color;
				o.uv = v.uv;
				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
				// sample the texture
				fixed4 col = Blur(_BlurTex, i.uv,_Radius * _BlurTex_TexelSize.xy);
				col.a = _Trans;
				return col;
			}
			ENDCG
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

saitoDeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值