今天遇到一个需要给UIText添加删除线的功能,以前博主一般是制作一个同样宽度的Image,盖在Text上,但是这次需要动态换行,所以就重写了Text的功能,具体代码如下。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DeleteLineText : Text
{
public float distance = 4f;
public float lineHeight = 4f;
public Color underLineColor;
private bool useUnderLineColor = true;
private List<UIVertex> textVertArr = new List<UIVertex>();
private int startIndex = 0;
private int endIndex = 0;
protected override void Start()
{
base.Start();
underLineColor = Color.red;
lineHeight = 5.0f;
distance = -15.0f;
}
protected override void OnPopulateMesh(VertexHelper toFill)
{
base.OnPopulateMesh(toFill); //渲染text字体的顶点
toFill.GetUIVertexStream(textVertArr); //toFill创建vertex流 vertex数组的长度是文字长度的6倍 因为一个文字有六个顶点
if (textVertArr.Count <= 0) return;
SetUnderLine(toFill);
}

本文介绍了一种在Unity中为Text组件添加动态删除线效果的方法。通过重写Text的OnPopulateMesh函数,获取文字顶点并绘制下划线,实现了根据文字内容动态变化的删除线效果。代码示例详细解释了如何找到文字底部的最小和最大位置,创建并绘制删除线。虽然此方法可能导致性能影响,但能提供更精确的删除线显示效果。

2万+

被折叠的 条评论
为什么被折叠?



