雷达图是显示数据的一个很直观的方式,今天就测试一下雷达图的案例
先看效果
1、首先创建一个Image,并挂载这个脚本,并在Inspector面板上进行实例化
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Lesson3 : MaskableGraphic
{
private float r, ang, bill;
public int maxNum;
public List<float> list_Num = new List<float>();
protected override void Awake()
{
Rect rect = gameObject.GetComponent<RectTransform>().rect;
//计算半径
r = rect.width < rect.height ? rect.width / 2 : rect.height /2;
//计算比例
bill = r / maxNum;
//计算角度
ang = Mathf.PI * 2 / list_Num.Count;
}
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
if (list_Num.Count < 3) return;
//添加顶点信息和颜色
vh.AddVert(Vector3.zero, Color.green, Vector2.zero);
for (int i = 0; i < list_Num.Count; i++)
{
//计算Sin值
float x = Mathf.Sin(ang * i) * list_Num[i] * bill;
//计算Cos值
float y = Mathf.Cos(ang * i) * list_Num[i] * bill;
//uv坐标的xy
float uvx = (x + r) / r * 2;
float uvy = (y + r) / r * 2;
//添加顶点信息和颜色
vh.AddVert(new Vector3(x, y, 0), Color.black, new Vector2(uvx, uvy));
if (i == 0)
{
//绘制网格图形
vh.AddTriangle(0, list_Num.Count, 1);
}
else
{
//绘制网格
vh.AddTriangle(0, i, i + 1);
}
}
}
}
2、再创建一个Image和Button并在Imag上挂载以下脚本,然后在Inspector面板实例化
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test618 : MaskableGraphic
{
private float r, ang, bill;
public int maxNum;
public List<float> list_Num = new List<float>();
public Button btn_test;
protected override void Awake()
{
Rect rect = GetComponent<RectTransform>().rect;
r = rect.width < rect.height ? rect.width / 2 : rect.height / 2;
bill = r / maxNum;
ang = Mathf.PI * 2 / list_Num.Count;
}
protected override void Start()
{
//这里的点击事件只做测试
btn_test.onClick.AddListener(() =>
{
//数据的真正信息可以在集合中依次赋值
for (int i = 0; i < list_Num.Count; i++)
{
list_Num[i] = Random.Range(1, maxNum + 1);
}
//重构
SetAllDirty();
});
}
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
if (list_Num.Count < 3) return;
vh.AddVert(Vector3.zero, Color.black, Vector2.zero);
for (int i = 0; i < list_Num.Count; i++)
{
float x = Mathf.Sin(ang * i) * list_Num[i] * bill;
float y = Mathf.Cos(ang * i) * list_Num[i] * bill;
float uvx = (x + r) / r * 2;
float uvy = (y + r) / r * 2;
vh.AddVert(new Vector3(x, y, 0), Color.grey, new Vector2(uvx, uvy));
if (i == 0)
{
vh.AddTriangle(0, list_Num.Count, 1);
}
else
{
vh.AddTriangle(0, i, i + 1);
}
}
}
}
注意一点:两次创建的Image必须处于同样位置,且层级渲染关系得清楚
谢谢观看!