哎!竭力想說清楚這個實現原理,並解釋清楚shader里面的算法,結果發現越解釋越不好理解,見諒!
一、實現目標:矩形四角是圓弧效果
二、實現的原理:通過每個角繪制1/4圓弧,剔除掉圓弧以外的部分。
原理圖:
實現代碼:
Shader "Custom/Test" { Properties { _MainTex ("Base (RGB)", 2D) = "white" {} } SubShader { Tags { "RenderType"="Opaque" } LOD 200 Blend SrcAlpha OneMinusSrcAlpha pass{ CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" sampler2D _MainTex; struct Input { fixed4 vertex:POSITION; fixed2 texcoord :TEXCOORD0; }; struct Output { fixed4 pos:POSITION; fixed2 uv :TEXCOORD0; }; Output vert(Input i) { Output o; o.pos = mul(UNITY_MATRIX_MVP,i.vertex); o.uv = i.texcoord; return o; } fixed4 frag(Output o):COLOR { fixed4 c = tex2D(_MainTex,o.uv); float2 uv = o.uv.xy- float2(0.5);//UV 坐標默認是(0 0)左下角,減0.5 是把UV的中心點移到(0 0) 這樣紋理坐標的范圍就是 (-0.5,-0.5)~(0.5,0.5) float rx = fmod(uv.x, 0.4); //fmod 求余函數,從原點開始 矩形的頂點坐標為0.4 float ry = fmod(uv.y, 0.4); float mx = step(0.4, abs(uv.x)); // if 0.4>abs(uv.x)?0:1 float my = step(0.4, abs(uv.y)); float filletAlpha = 1 - mx * my * step(0.1, length(half2(rx,ry))); //如果在圓角矩形內,alpha值為1 否則為0。 和0.1做比較 因為圓角半徑為0.1 c = fixed4(c.r,c.g,c.b,filletAlpha); return c; } ENDCG } } }
注意:直接理解上面的計算圓角部分 有點難以理解,可以套到具體圖里面 看效果推理就可以。
實現效果:
參考:
http://imgtec.eetrend.com/blog/3608
http://blog.sina.com.cn/s/blog_89d90b7c0102vayz.html