游戏开发过程中难免会遇到要将矩形图片切成圆形的需求,但是Unity原生Mask组件效率低下,如果某个界面有大量这样的需求,我们就不得不实现一种更高效的Mask遮罩。
原生Mask组件的缺陷
- 基于Stencil Buffer实现,本身会额外占用2个Draw Call,一个设置Stencil Buffer,一个还原Stencil Buffer
- 严重的锯齿
- 不利于合批,Mask内的元素无法与Mask外的元素合批
解决方案
新的方案我们需要解决原生Mask的问题,不增加Draw Call,边缘柔和。这里我们采用自定义Shader,主图与遮罩图进行Alpha混合方案。
实现效果如下:
效果
因为要两种图片进行混合,所以我们的Shader要额外传入一张Mask贴图,然后在FragmentShader中将两种贴图的Alpha值相乘,如果Mask贴图的Alpha值为0,最终颜色的Alpha值为0,相当于剪裁掉了,Mask贴图的Alpha值为1,则保持原样,而0-1的中间值则可以很好的过渡,使剪裁边缘更加柔和。核心代码很简单:
fixed4 frag(v2f IN) : SV_Target
{
half4 color = tex2D(_MainTex, IN.texcoord);
half4 maskColor = tex2D(_Mask, IN.texcoord);
color.a *= maskColor.a;
return color;
}
到这里,其实还有一点小小的问题,Main Texture跟Mask Texture共用了一套uv即IN.texcoord
,如果Main Texture是散图的话没有问题,如果最后打包成了图集,问题就出现了,Mask的uv不对。所以对于Mask贴图我们得单独采用一套uv。
对于顶点属性的修改,Unity提供了一个基类BaseMeshEffect
,我们只需要继承BaseMeshEffect
实现ModifyMesh
接口完成Mask uv的计算。完整的代码如下:
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设置一下,传入第二套uv
Additional Shader Channels
网友评论