UILineRender

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UILineRender : Graphic
{
    //  线宽度
    public float thiness = 10;
    //  线路径点
    public List points;

    protected override void OnPopulateMesh(VertexHelper vh)
    {
        //  清空
        vh.Clear();
        //  单点不成线
        if (points.Count < 2)
            return;
        //  绘制
        for(int i = 0; i < points.Count - 1; ++i)
        {
            DrawLine(points[i], points[i + 1], vh);
        }

    }

    //  绘制线
    void DrawLine(Vector2 start, Vector2 end, VertexHelper vh)
    {
        // 走向
        Vector3 dir = end - start;

        //  走向法线
        Vector3 tangent = (Quaternion.Euler(0, 0, 90) * dir).normalized;

        UIVertex vertex = UIVertex.simpleVert;
        vertex.color = color;

        int index = vh.currentVertCount;
        //  创建顶点
        vertex.position = (tangent * thiness / 2) + new Vector3(start.x, start.y, 0);
        vh.AddVert(vertex);

        vertex.position = (-tangent * thiness / 2) + new Vector3(start.x, start.y, 0);
        vh.AddVert(vertex);

        vertex.position = (tangent * thiness / 2) + new Vector3(end.x, end.y, 0);
        vh.AddVert(vertex);

        vertex.position = (-tangent * thiness / 2) + new Vector3(end.x, end.y, 0);
        vh.AddVert(vertex);
        //  创建三角形
        vh.AddTriangle(index, index + 1, index + 3);
        vh.AddTriangle(index + 3, index + 2, index);
        //  不是起点,需要创建连接部分
        if (index != 0)
        {
            vh.AddTriangle(index - 2, index - 1, index + 1);
            vh.AddTriangle(index + 1, index, index - 2);
        }
    }
}

你可能感兴趣的:(UILineRender)