本文主要是介绍Unity 使用代码生成饼状图 PieChart,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前言:
之前工作需要实现饼状图,这里记录一下用代码生成饼状图的方法.
原理:
1.原理很简单,通过创建网格绘制各个饼状图基块,然后按角度合成即可.
2.如何创建网格,请直接看官方文档.
3.图像分析:
4.下面是生成饼状图的核心代码:
/// <summary>/// 生成饼状图./// </summary>private void GeneratePieChart(){float rot = 360.0f / num;for (int i = 0; i < num; i++){Transform child = GenerateChildPieChart(3, num, height); //饼状图基块.child.localRotation = Quaternion.Euler(0, rot * i, 0); child.localPosition = new Vector3(0, height / 2.0f, 0); child.gameObject.layer = LayerMask.NameToLayer("UI");child.SetParent(m_Transform, false);pieChartList.Add(child);}m_Transform.localScale = Vector3.one * 20;m_Transform.localRotation = Quaternion.Euler(90, 0, 0);}/// <summary>/// 创建饼状图基块./// </summary>/// <param name="r">半径</param>/// <param name="num">份数</param>/// <param name="height">厚度</param>/// <returns></returns>private Transform GenerateChildPieChart(float r, int num, float height){float y = r * Mathf.Sin((180.0f / num) * Mathf.Deg2Rad);float x = Mathf.Sqrt(r * r - y * y);Vector3 origin1 = new Vector3(0, 0, 0);Vector3 origin2 = new Vector3(x, 0, y);Vector3 origin3 = new Vector3(x, 0, -y);Vector3 offset = new Vector3(0, height, 0);Mesh mesh = new Mesh();Vector3[] vertices = new Vector3[6];vertices[0] = origin1; vertices[1] = origin2;vertices[2] = origin3;vertices[3] = vertices[0] - offset; vertices[4] = vertices[1] - offset;vertices[5] = vertices[2] - offset;int[] triangles = new int[48] { //双面都要.0, 1, 2, 3, 4, 5, //顺时针 正面.0, 2, 5, 0, 5, 3, 0, 1, 4, 0, 4, 3,2, 1, 4, 2, 4, 5,0, 2, 1, 3, 5, 4, //逆时针 反面.0, 5, 2, 0, 3, 5, 0, 4, 1, 0, 3, 4,2, 4, 1, 2, 5, 4 };mesh.vertices = vertices;mesh.triangles = triangles;GameObject temp = new GameObject();MeshFilter meshFilter = temp.AddComponent<MeshFilter>();meshFilter.mesh = mesh;MeshRenderer meshRenderer = temp.AddComponent<MeshRenderer>();//meshRenderer.material.shader = Shader.Find("Diffuse");meshRenderer.material = material_Other;return temp.transform;}
项目代码源文件.
完毕.
这篇关于Unity 使用代码生成饼状图 PieChart的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!