一、简介
雷达图:雷达图是以从同一点开始的轴上表示的三个或更多个定量变量的二维图表的形式显示多变量数据的图形方法。轴的相对位置和角度通常是无信息的。 雷达图也称为网络图,蜘蛛图,星图,蜘蛛网图,不规则多边形,极坐标图或Kiviat图。它相当于平行坐标图,轴径向排列。
想必大家在观看LoL比赛时总能看见类似这样的图片 这就是雷达图
游戏中的雷达图
二、具体实现
下面我将用Unity制作一个简易的雷达图
public class RadarMap : MaskableGraphic
{
public Button btn;
//圆心到每条边的距离
public float[] list = new float[5];
public float ww = 1;
public Color wwColor = Color.red;
protected override void Start()
{
base.Start();
if (btn != null)
{
btn.onClick.AddListener(() =>
{
for (int i = 0; i < list.Length; i++)
{
list[i] = Random.Range(1, 100);
}
//清除上次绘制的数据
//SetAllDirty();
SetVerticesDirty();
});
}
}
protected override void OnPopulateMesh(VertexHelper vh)
{
base.OnPopulateMesh(vh);
if (list.Length >= 3)
{
Rect rect = this.rectTransform.rect;
vh.Clear();
vh.AddVert(Vector3.zero, color, new Vector2(0.5f, 0.5f));
float angle = 2 * Mathf.PI / list.Length;
// 用外接圆的半径/数组的最大边 ==比例 保证绘制不超出ui
float p = rect.width < rect.height ? rect.width / 2 / list.Max() : rect.height / 2 / list.Max();
for (int i = 0; i < list.Length; i++)
{
//顶点坐标
float x = Mathf.Sin(angle * i) * list[i] * p;
float y = Mathf.Cos(angle * i) * list[i] * p;
float uvx = (x + rect.width / 2) / rect.width;
float uvy = (y + rect.height / 2) / rect.height;
vh.AddVert(new Vector3(x, y, 0), color, new Vector2(uvx, uvy));
if (i == 0)
{
vh.AddTriangle(0, list.Length, 1);
}
else
{
vh.AddTriangle(0, i, i + 1);
}
}
//使用过的顶点数量 上面绘制过雷达图有6个顶点 所以数组长度+1
int next = list.Length + 1;
//红色边框
for (int i = 0; i < list.Length; i++)
{
//红色边框最外层顶点
float x0 = Mathf.Sin(angle * i) * (list[i] * p - ww);
float y0 = Mathf.Cos(angle * i) * (list[i] * p - ww);
float uvx0 = (x0 + rect.width / 2) / rect.width;
float uvy0 = (y0 + rect.height / 2) / rect.height;
vh.AddVert(new Vector3(x0, y0, 0), wwColor, new Vector2(uvx0, uvy0));
//红色边框最内层顶点
float x = Mathf.Sin(angle * i) * list[i] * p;
float y = Mathf.Cos(angle * i) * list[i] * p;
float uvx = (x + rect.width / 2) / rect.width;
float uvy = (y + rect.height / 2) / rect.height;
vh.AddVert(new Vector3(x, y, 0), wwColor, new Vector2(uvx, uvy));
if (i == list.Length - 1)
{
vh.AddTriangle(i * 2 + next, (i * 2) + 1 + next, 0 + next);
vh.AddTriangle((i * 2) + 1 + next, 1 + next, 0 + next);
}
else
{
vh.AddTriangle(i * 2 + next, (i * 2) + 1 + next, (i + 1) * 2 + next);
vh.AddTriangle((i * 2) + 1 + next, (i + 1) * 2 + 1 + next, (i + 1) * 2 + next);
}
}
}
}
}