游戲開(kāi)發(fā)過(guò)程中難免會(huì)遇到要將矩形圖片切成圓形的需求晦嵌,但是Unity原生Mask組件效率低下拷姿,如果某個(gè)界面有大量這樣的需求惭载,我們就不得不實(shí)現(xiàn)一種更高效的Mask遮罩。
原生Mask組件的缺陷
- 基于Stencil Buffer實(shí)現(xiàn)响巢,本身會(huì)額外占用2個(gè)Draw Call,一個(gè)設(shè)置Stencil Buffer踪古,一個(gè)還原Stencil Buffer
- 嚴(yán)重的鋸齒
- 不利于合批,Mask內(nèi)的元素?zé)o法與Mask外的元素合批
解決方案
新的方案我們需要解決原生Mask的問(wèn)題伏穆,不增加Draw Call拘泞,邊緣柔和。這里我們采用自定義Shader枕扫,主圖與遮罩圖進(jìn)行Alpha混合方案。
實(shí)現(xiàn)效果如下:
因?yàn)橐獌煞N圖片進(jìn)行混合诗鸭,所以我們的Shader要額外傳入一張Mask貼圖,然后在FragmentShader中將兩種貼圖的Alpha值相乘只泼,如果Mask貼圖的Alpha值為0请唱,最終顏色的Alpha值為0聚至,相當(dāng)于剪裁掉了甚亭,Mask貼圖的Alpha值為1役纹,則保持原樣策州,而0-1的中間值則可以很好的過(guò)渡,使剪裁邊緣更加柔和汁胆。核心代碼很簡(jiǎn)單:
fixed4 frag(v2f IN) : SV_Target
{
half4 color = tex2D(_MainTex, IN.texcoord);
half4 maskColor = tex2D(_Mask, IN.texcoord);
color.a *= maskColor.a;
return color;
}
到這里铸题,其實(shí)還有一點(diǎn)小小的問(wèn)題探熔,Main Texture跟Mask Texture共用了一套u(yù)v即IN.texcoord
其垄,如果Main Texture是散圖的話沒(méi)有問(wèn)題,如果最后打包成了圖集漏健,問(wèn)題就出現(xiàn)了茎毁,Mask的uv不對(duì)橡卤。所以對(duì)于Mask貼圖我們得單獨(dú)采用一套u(yù)v。
對(duì)于頂點(diǎn)屬性的修改,Unity提供了一個(gè)基類BaseMeshEffect
,我們只需要繼承BaseMeshEffect
實(shí)現(xiàn)ModifyMesh
接口完成Mask uv的計(jì)算延曙。完整的代碼如下:
C#代碼:
using UnityEngine;
using UnityEngine.Sprites;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class MaskImage : BaseMeshEffect
{
private Image _image;
protected override void Awake()
{
base.Awake();
_image = GetComponent<Image>();
}
public override void ModifyMesh(VertexHelper vh)
{
if (!IsActive())
return;
var overrideSprite = _image.overrideSprite;
var uv = overrideSprite != null ? DataUtility.GetOuterUV(overrideSprite) : Vector4.zero;
var uvWidth = uv.z - uv.x;
var uvHeight = uv.w - uv.y;
if (uvWidth == 0 || uvHeight == 0)
return;
var vertCount = vh.currentVertCount;
var vert = new UIVertex();
for (var i = 0; i < vertCount; ++i)
{
vh.PopulateUIVertex(ref vert, i);
vert.uv1.x = (vert.uv0.x - uv.x) / uvWidth;
vert.uv1.y = (vert.uv0.y - uv.y) / uvHeight;
vh.SetUIVertex(vert, i);
}
}
}
Shader代碼:
Shader "Custom/ImageMask"
{
Properties
{
[PerRendererData] _MainTex ("Texture", 2D) = "white" {}
_Mask ("Mask", 2D) = "white" {}
_Color ("Tint", Color) = (1, 1, 1, 1)
_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
[Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0
}
SubShader
{
Tags
{
"Queue"="Transparent"
"IgnoreProjector"="True"
"RenderType"="Transparent"
"PreviewType"="Plane"
"CanUseSpriteAltas"="True"
}
Stencil
{
Ref [_Stencil]
Comp [_StencilComp]
Pass [_StencilOp]
ReadMask [_StencilReadMask]
WriteMask [_StencilWriteMask]
}
Cull Off
ZWrite Off
ZTest [unity_GUIZTestMode]
Blend SrcAlpha OneMinusSrcAlpha
ColorMask [_ColorMask]
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "UnityUI.cginc"
#pragma multi_compile __ UNITY_UI_ALPHACLIP
struct appdata_t
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
struct v2f
{
float4 vertex : SV_POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
float4 worldPosition : TEXCOORD2;
};
fixed4 _Color;
fixed4 _TextureSampleAdd;
float4 _ClipRect;
v2f vert(appdata_t IN)
{
v2f OUT;
OUT.worldPosition = IN.vertex;
OUT.vertex = UnityObjectToClipPos(OUT.worldPosition);
OUT.texcoord = IN.texcoord;
OUT.texcoord1 = IN.texcoord1;
OUT.color = IN.color * _Color;
return OUT;
}
sampler2D _MainTex;
sampler2D _Mask;
fixed4 frag(v2f IN) : SV_Target
{
half4 color = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd) * IN.color;
half4 maskColor = tex2D(_Mask, IN.texcoord1);
color.a *= maskColor.a;
color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);
#ifdef UNITY_UI_ALPHACLIP
clip (color.a - 0.001);
#endif
return color;
}
ENDCG
}
}
}
最后,我們需要在上層Canvas設(shè)置一下锄码,傳入第二套u(yù)v