UGUI 文本加粗

UGUI 文本加粗_第1张图片

UGUI 文本加粗_第2张图片

这是用的Aril字体,通常情况下,直接用达不到这样粗的效果,所以需要重新写一个字体效果,类似描边的效果。

上面的图片就是效果和所设置的参数。

下面是代码,参考其他人的代码改编的

using UnityEngine;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class BoldTextEffect : BaseMeshEffect
{
    [Range(1, 5)] public int Strength = 5;
    public int startBIndex = 0;
    public int endBIndex = 999;

    private Text m_Text = null;

    private Text TextComp
    {
        get
        {
            if (m_Text == null)
            {
                m_Text = GetComponent();
            }

            return m_Text;
        }
    }

    public Color effectColor = Color.white;

    protected void ApplyShadowZeroAlloc(List verts, Color32 color, int start, int end, float x, float y)
    {
        int num = verts.Count + end - start;
        if (verts.Capacity < num)
            verts.Capacity = num;
        for (int index = start; index < end; ++index)
        {
            UIVertex vert = verts[index];
            verts.Add(vert);
            Vector3 position = vert.position;
            position.x += x;
            position.y += y;
            vert.position = position;
            Color32 color32 = color;
            vert.color = color32;
            verts[index] = vert;
        }
    }

    private static readonly Regex s_BoldBeginRegex = new Regex("", RegexOptions.Singleline);
    private static readonly Regex s_BoldEndRegex = new Regex("", RegexOptions.Singleline);

    private MatchCollection begin = null;
    private MatchCollection end = null;


    public override void ModifyMesh(VertexHelper vh)
    {
        if (!IsActive())
        {
            return;
        }

        List verts = new List();
        vh.GetUIVertexStream(verts);

        begin = s_BoldBeginRegex.Matches(TextComp.text);
        end = s_BoldEndRegex.Matches(TextComp.text);

        if (begin != null && end != null)
        {
            int i = startBIndex;
            if (i < 0) i = 0;
            for (; i < endBIndex && i < begin.Count && i < end.Count; ++i)
            {
                ApplyShadowZeroAlloc(verts, effectColor, begin[i].Index * 6, end[i].Index * 6, 1, 0f);
                for (int j = 0; j < Strength; ++j)
                {
                    ApplyShadowZeroAlloc(verts, effectColor, begin[i].Index * 6, end[i].Index * 6, -1, 0f);
                }
            }
        }

        vh.Clear();
        vh.AddUIVertexTriangleStream(verts);
    }

}

 

你可能感兴趣的:(Unity)