Unity 雷达图

1.原理篇
UGUI是一个CanvasRenderer进行绘制,所有的控件和可显示的元素都是Graphic。
比方说Image,Text 都是继承Graphic,有Graphic肯定是要有CanvasRenderer的。关于Graphic的一些绘制原理可以查看参考网站的第一个网址。

我这里绘制的雷达图,也是在UGUI上,通过继承Graphic,连接中心点和多边形的顶点绘制三角形绘制的。

2.最后来上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// 绘制多边形雷达图
/// 以下是五边形的顶点示意图,以中心点为原点,绘制5个三角形,012,023,034,045,051
///
/// 2
///
/// 3 0 1
///
/// 4 5
/// </summary>
[AddComponentMenu("UI/Polygon")]
public class Polygon : Graphic
{
private List<Vector2> vertexList = new List<Vector2>(); //顶点的坐标,顶点数量必须大于2
public List<float> VertextRanges = new List<float>() { 1,1,1,1,1 };
private int PointCount = 5;
public float Max_Value = 100.0f;
private Vector2 OriPoint = new Vector2(0, 0);
protected override void Start()
{
base.Start();
Init();
}
private void Init()
{
vertexList.Clear();
for(int i=0;i<PointCount;i++)
{
float cornerAngle = 2.0f * Mathf.PI / 360 * (18 + (360/PointCount) * i);
vertexList.Add(new Vector2(Max_Value * VertextRanges[i] * Mathf.Cos(cornerAngle), Max_Value * VertextRanges[i] * Mathf.Sin(cornerAngle)));
}
}
protected override void OnPopulateMesh(VertexHelper vh)
{
base.OnPopulateMesh(vh);
Init();
List<UIVertex> targetVertexList = new List<UIVertex>();
for(int i=0;i<vertexList.Count;i++)
{
UIVertex oriVertex = new UIVertex();
oriVertex.position = OriPoint;
oriVertex.color = color;
targetVertexList.Add(oriVertex);
for (int j =0;j<2;j++)
{
UIVertex vertex = new UIVertex();
if(i+j >= vertexList.Count)
{
vertex.position = vertexList[i + j - vertexList.Count];
}else
{
vertex.position = vertexList[i + j];
}
vertex.color = color;
targetVertexList.Add(vertex);
}
}
vh.Clear();
vh.AddUIVertexTriangleStream(targetVertexList);
}
}

效果图:
paste image

参考网址:http://blog.csdn.net/langresser_king/article/details/46928197
http://www.xshadow.org/index.php/archives/73

坚持原创技术分享,您的支持将鼓励我继续创作!