Análisis del código fuente UIGU 15: Máscara

Código fuente 15: Máscara

public class Mask : UIBehaviour, ICanvasRaycastFilter, IMaterialModifier
{
    [NonSerialized]
    private RectTransform m_RectTransform;

    [SerializeField]
    private bool m_ShowMaskGraphic = true;

	...

}

El componente Mask hereda UIBehaviour e implementa dos interfaces ICanvasRaycastFilter e IMaterialModifier.

ICanvasRaycastFilter: si RectTransform contiene el punto visto desde la cámara

    public virtual bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
    {
        if (!isActiveAndEnabled)
            return true;

        return RectTransformUtility.RectangleContainsScreenPoint(rectTransform, sp, eventCamera);
    }

IMaterialModifier: Heredado de la interfaz IMaterialModifier, MaskableGraphic también hereda esta interfaz, este método se utiliza para modificar el material obtenido para lograr el efecto de enmascaramiento.


De manera similar a RectMask2D, el uso de Mask debe coordinarse con el IMaskable enmascarado, que es el componente MaskableGraphic. Pero a diferencia del componente RectMask2D, Mask debe estar vinculado a un Gráfico para enmascarar. Los componentes mostrados en UGUI básicamente heredan el componente MaskableGraphic, lo que significa que cuando MaskableGraphic se usa como máscara, es necesario vincular un componente Máscara. Al mismo tiempo, el Texto y la Imagen están enmascarados cuando son responsables de la visualización. MaskableGraphic tiene atributos para distinguirlo.

    /// <summary>
    /// Is this graphic the graphic on the same object as a Mask that is enabled.
    /// </summary>
    /// <remarks>
    /// If toggled ensure to call MaskUtilities.NotifyStencilStateChanged(this); manually as it changes how stenciles are calculated for this image.
    /// </remarks>
    public bool isMaskingGraphic
    {
        get { return m_IsMaskingGraphic; }
        set
        {
            if (value == m_IsMaskingGraphic)
                return;

            m_IsMaskingGraphic = value;
        }
    }

La asignación de isMaskingGraphic es cuando se vincula el componente Máscara, se establece en Verdadero cuando el componente Máscara está activado y en Falso cuando está cerrado.

Código de máscara:

    protected override void OnEnable()
    {
        base.OnEnable();
        if (graphic != null)
        {
            graphic.canvasRenderer.hasPopInstruction = true;
            graphic.SetMaterialDirty();

            // Default the graphic to being the maskable graphic if its found.
            if (graphic is MaskableGraphic)
                (graphic as MaskableGraphic).isMaskingGraphic = true;
        }

        MaskUtilities.NotifyStencilStateChanged(this);
    }

    protected override void OnDisable()
    {
        // we call base OnDisable first here
        // as we need to have the IsActive return the
        // correct value when we notify the children
        // that the mask state has changed.
        base.OnDisable();
        if (graphic != null)
        {
            graphic.SetMaterialDirty();
            graphic.canvasRenderer.hasPopInstruction = false;
            graphic.canvasRenderer.popMaterialCount = 0;

            if (graphic is MaskableGraphic)
                (graphic as MaskableGraphic).isMaskingGraphic = false;
        }

        StencilMaterial.Remove(m_MaskMaterial);
        m_MaskMaterial = null;
        StencilMaterial.Remove(m_UnmaskMaterial);
        m_UnmaskMaterial = null;

        MaskUtilities.NotifyStencilStateChanged(this);
    }

Graphic.SetMaterialDirty(); es establecer la etiqueta para la reconstrucción en True. El análisis de gráficos se analizó anteriormente.

public static void NotifyStencilStateChanged(Component mask)
    {
        var components = ListPool<Component>.Get();
        mask.GetComponentsInChildren(components);
        for (var i = 0; i < components.Count; i++)
        {
            if (components[i] == null || components[i].gameObject == mask.gameObject)
                continue;

            var toNotify = components[i] as IMaskable;
            if (toNotify != null)
                toNotify.RecalculateMasking();
        }
        ListPool<Component>.Release(components);
    }

MaskUtilities.NotifyStencilStateChanged(this) notifica a todos los subobjetos que implementan IMaskable para volver a calcular la máscara. De hecho, finalmente regresé a Graphic para llamar a SetMaterialDirty, actualizar el material UpdateMaterial y modificar los datos de vértice y los datos de material de Graphic. Es por eso que MaskableGraphic necesita implementar IMaterialModifier.

Supongo que te gusta

Origin blog.csdn.net/NippyLi/article/details/123601941
Recomendado
Clasificación