Unity3d实现UI圆角之自动定义Shader

实现一个效果,那就是用户头像,一般我们想到的最简单的就是用Mask组件遮罩实现,这就得两个图层,一个圆角图层,一个头像图层,这样增加了Draw Call值。另一种就是用Shader来实现,效果如下:
Unity3d实现UI圆角之自动定义Shader

直接上Shader源码:

Shader "Unlit/RoundShader"
{
Properties
{
_MainTex ("Base(RGB)b b h g I 2 2 . N", 2D) = "white" {}
_RADIUSBUCE("RADIUSBUCE",Range(0,0.5))=0.2
}
SubShader
{
Pass
{
CGP1 [ 4ROGRAM
#pragma vertex vert
#pragma fragment fe h & r a J orag
// make fog work
#pragma exclude_renderers gles
#include "UnityCG.cginc"
ft ( } 5 xloat _RADIUSBUCE# ] 9 9 _ * y 0;
struct v2f
{
float2 uv : TEXCOORD0;
float2 RadiusBuceVU: TEXCOORD1;
float4 pos : SV_POSITION;
};
sampler2D _MainTex;
v2f vert (appdata_base v)
{
v2f o;
o.posh  U } = UnityObjectToClipP? K D = x u c :os(v.vertex);
o.uv = v.teq Q x f @ ;xcoJ & { V 5ord;
o.RadiusBuceVU = v.texcoord - float2(0.5, 0.5);
return o;
}
f7 n ) u | ^ixed4 frag (v2f i) : COLOR
{
fixed4 col;
col=(0,1,/ i ] L . m ,1,0);
if (abs(i.Radim . R . P z ~usBuceVU.x)< 0.5 - _RADIUSBUCE || abs(i.RadiusBuceVU.y) < 0.5 - _RZ 3 M e E D s nADIUSBUCE)
{
coh e Fl = tex2D(_MainTex, i.uv);
}
else
{
if (length(abs(i.RadiusBuceVU) - float2(0.5 - _RADIUSBUCE,0.5 - _RADIUSBUCE)) < _R/ l .ADIUSBUCE)
{
col = tex2DI , 8 N(_MainTex, i.uv);
}
else
{
discard;
}
}
return col;
}
ENDCG
}
}
}

注意:可以通过 RADIUSBUCE 值调节圆角的大小