UGUI中绘制多边形雷达图

PolygonExample
原理是使用数个三角形拼成一个多边形,多边形的颜色就取了Graphic中的颜色

代码如下

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

/// <summary>
/// 绘制多边形雷达图
/// 以下是五边形的顶点示意图,123为一个三角形,234为一个三角形,345为一个三角形,三个三角形拼接变成五边形
/// 
///         3
/// 
/// 1                5
/// 
///     2       4
/// </summary>
[AddComponentMenu("UI/Polygon")]
public class Polygon : Graphic
{
    public List<Vector2> vertexList;    //顶点的坐标,顶点数量必须大于2
    
    protected override void OnPopulateMesh(VertexHelper vh)
    {
        base.OnPopulateMesh(vh);
        List<UIVertex> targetVertexList = new List<UIVertex>();
        int triangleCount = vertexList.Count - 2;
        for (int i = 0; i < triangleCount; i++)
        {
            for (int j = 0; j < 3; j++)     //三角形的三个点
            {
                UIVertex vertex = new UIVertex();
                vertex.position = vertexList[i + j];
                vertex.color = color;
                targetVertexList.Add(vertex);
            }
        }

        vh.Clear();
        vh.AddUIVertexTriangleStream(targetVertexList);
    }
}
Tags:,