Mask(遮罩)元件是Unity UGUI中的一個重要元件,用於限制子物件的可見區域。通過設定遮罩元件,可以實現一些特殊效果,如顯示部分圖片、裁剪文字等。
Mask元件通過將子物件與遮罩物件進行比較,只顯示與遮罩物件重疊的部分,從而實現遮罩效果。遮罩物件可以是任意形狀的UI元素,如Image、RawImage等。
using UnityEngine;
using UnityEngine.UI;
public class ImageMaskExample : MonoBehaviour
{
public Image mask;
public RawImage image;
void Start()
{
mask.sprite = Resources.Load<Sprite>("MaskImage");
image.texture = Resources.Load<Texture>("Image");
image.transform.SetParent(mask.transform);
mask.GetComponent<Mask>().showMaskGraphic = false;
}
}
操作步驟:
using UnityEngine;
using UnityEngine.UI;
public class TextMaskExample : MonoBehaviour
{
public Text mask;
public Text text;
void Start()
{
mask.text = "Mask Text";
text.text = "Hello World";
text.transform.SetParent(mask.transform);
mask.GetComponent<Mask>().showMaskGraphic = false;
}
}
操作步驟:
using UnityEngine;
using UnityEngine.UI;
public class DynamicMaskExample : MonoBehaviour
{
public Image mask;
public RawImage image;
void Start()
{
mask.sprite = Resources.Load<Sprite>("MaskImage");
image.texture = Resources.Load<Texture>("Image");
image.transform.SetParent(mask.transform);
mask.GetComponent<Mask>().showMaskGraphic = false;
// 動態修改遮罩物件的形狀
mask.rectTransform.sizeDelta = new Vector2(200, 200);
}
}
操作步驟:
using UnityEngine;
using UnityEngine.UI;
public class InteractionMaskExample : MonoBehaviour
{
public Image mask;
public RawImage image;
void Start()
{
mask.sprite = Resources.Load<Sprite>("MaskImage");
image.texture = Resources.Load<Texture>("Image");
image.transform.SetParent(mask.transform);
mask.GetComponent<Mask>().showMaskGraphic = false;
mask.GetComponent<Mask>().maskInteraction = MaskInteraction.VisibleInsideMask;
}
}
操作步驟:
using UnityEngine;
using UnityEngine.UI;
public class AlphaCutoffMaskExample : MonoBehaviour
{
public Image mask;
public RawImage image;
void Start()
{
mask.sprite = Resources.Load<Sprite>("MaskImage");
image.texture = Resources.Load<Texture>("Image");
image.transform.SetParent(mask.transform);
mask.GetComponent<Mask>().showMaskGraphic = false;
mask.GetComponent<Mask>().alphaCutoff = 0.5f;
}
}
操作步驟: