Archived
77 lines
2.9 KiB
C#
77 lines
2.9 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
namespace XericLibrary
|
|
{
|
|
/// <summary>
|
|
/// UILineRenderer 是一个用于在 UI 上绘制连续线条的组件
|
|
/// 支持设置线条厚度、居中显示,并为线段之间添加斜角边缘
|
|
/// 继承自 MaskableGraphic,可与 UI 遮罩系统配合使用
|
|
/// </summary>
|
|
[RequireComponent(typeof(CanvasRenderer))]
|
|
public class UILineRenderer : MaskableGraphic
|
|
{
|
|
/// <summary>
|
|
/// 线条的顶点数组,至少需要 2 个点才能绘制线条
|
|
/// 点的坐标基于本地空间,中心点由 center 属性控制
|
|
/// </summary>
|
|
public Vector2[] points;
|
|
|
|
/// <summary>
|
|
/// 线条的厚度,单位为像素
|
|
/// </summary>
|
|
public float thickness = 10f;
|
|
|
|
/// <summary>
|
|
/// 是否将线条居中显示
|
|
/// true: 线条将以组件中心为原点
|
|
/// false: 线条将以组件左下角为原点
|
|
/// </summary>
|
|
public bool center = true;
|
|
|
|
/// <summary>
|
|
/// 重写 MaskableGraphic 的方法,用于生成线条的网格
|
|
/// 当 UI 需要重建时会自动调用此方法
|
|
/// </summary>
|
|
/// <param name="vh">用于构建网格的 VertexHelper 对象</param>
|
|
protected override void OnPopulateMesh(VertexHelper vh)
|
|
{
|
|
// 清空现有的网格数据
|
|
vh.Clear();
|
|
|
|
// 至少需要 2 个点才能绘制线条
|
|
if (points.Length < 2)
|
|
return;
|
|
|
|
// 计算线路总长度
|
|
float totalLength = UILineRendererUtils.CalculateTotalLength(points);
|
|
float currentLength = 0f;
|
|
|
|
// 遍历所有点,创建线段并添加到网格中
|
|
for (int i = 0; i < points.Length-1; i++)
|
|
{
|
|
// 使用静态工具方法创建当前点与下一个点之间的线段
|
|
// 传递当前累积长度和总长度用于UV坐标计算
|
|
UILineRendererUtils.CreateLineSegment(points[i], points[i+1], thickness, center, rectTransform.sizeDelta, color, vh, currentLength, totalLength);
|
|
|
|
// 更新累积长度
|
|
currentLength += Vector2.Distance(points[i], points[i+1]);
|
|
|
|
// 计算当前线段的顶点索引(每个线段包含 5 个顶点)
|
|
int index = i * 5;
|
|
|
|
// 添加线段的两个三角形(构成矩形线段)
|
|
vh.AddTriangle(index, index+1, index+3);
|
|
vh.AddTriangle(index+3, index+2, index);
|
|
|
|
// 为线段之间添加斜角边缘
|
|
// 使用上一个线段的终点和当前线段的起点创建过渡三角形
|
|
if (i != 0)
|
|
{
|
|
vh.AddTriangle(index, index-1, index-3);
|
|
vh.AddTriangle(index+1, index-1, index-2);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |