1.效果
2.原理
通过检测alpha的变化梯度可以确定边缘.也可以通过周围alpha的值来扩大显示范围,先画出一个背景来.
3.代码
Shader "Custom/Outline2D" { Properties { _MainTex ("Base (RGB)", 2D) = "white" {} _Color("Outline Color", color) = (1,1,1,1) _Outline("Outline Width",Range(0,0.2))=0.02 } SubShader { //画轮廓 pass{ Cull Off ZWrite Off CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" sampler2D _MainTex; float4 _Color; float _Outline; struct v2f{ float4 pos:SV_POSITION; float2 texcoord:TEXCOORD; }; v2f vert(appdata_full v){ v2f o; o.pos = mul(UNITY_MATRIX_MVP, v.vertex); o.texcoord = v.texcoord; return o; } float4 frag(v2f i) :COLOR{ float2 t=i.texcoord; float4 c = tex2D(_MainTex, t); float2 coord0=float2(t[0],t[1]+_Outline); float2 coord1=float2(t[0],t[1]-_Outline); float2 coord2=float2(t[0]+_Outline,t[1]); float2 coord3=float2(t[0]-_Outline,t[1]); bool b=(tex2D(_MainTex, coord0).a)||(tex2D(_MainTex, coord1).a)||(tex2D(_MainTex, coord2).a)||(tex2D(_MainTex, coord3).a); if(!b) clip(tex2D(_MainTex, coord0).a-0.1); return _Color; } ENDCG } //正常显示 pass{ Cull off ZWrite On CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" sampler2D _MainTex; float4 _Color; float _Outline; struct v2f{ float4 pos:SV_POSITION; float2 texcoord:TEXCOORD; }; v2f vert(appdata_full v){ v2f o; o.pos = mul(UNITY_MATRIX_MVP, v.vertex); o.texcoord = v.texcoord; return o; } float4 frag(v2f i) :COLOR{ float4 c = tex2D(_MainTex, i.texcoord); clip (c.a - 0.1); return c; } ENDCG } } FallBack "Diffuse" }