版本:2023.2+
此示例演示如何使用矢量 API 在编辑器和运行时__ UI__(即用户界面,User Interface)让用户能够与您的应用程序进行交互。Unity 目前支持三种 UI 系统。更多信息
See in Glossary 中创建图形。
此示例在 VisualElement 上生成一个饼图,并将其显示在编辑器和运行时 UI 中。
可以在此 GitHub 代码仓库中找到此示例创建的完整文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发者。在开始之前,请熟悉以下内容:
创建一个 C# 脚本,使用矢量 API 中的 Arc 和 Fill 方法将饼图绘制到视觉元素中。
pie-chart 的文件夹来存储文件。pie-chart 文件夹中,创建一个名为 PieChart.cs 的 C# 脚本,其中包含以下内容:using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
[UxmlElement]
public partial class PieChart : VisualElement
{
float m_Radius = 100.0f;
float m_Value = 40.0f;
public float radius
{
get => m_Radius;
set
{
m_Radius = value;
}
}
public float diameter => m_Radius * 2.0f;
public float value {
get { return m_Value; }
set { m_Value = value; MarkDirtyRepaint(); }
}
public PieChart()
{
generateVisualContent += DrawCanvas;
}
void DrawCanvas(MeshGenerationContext ctx)
{
var painter = ctx.painter2D;
painter.strokeColor = Color.white;
painter.fillColor = Color.white;
var percentage = m_Value;
var percentages = new float[] {
percentage, 100 - percentage
};
var colors = new Color32[] {
new Color32(182,235,122,255),
new Color32(251,120,19,255)
};
float angle = 0.0f;
float anglePct = 0.0f;
int k = 0;
foreach (var pct in percentages)
{
anglePct += 360.0f * (pct / 100);
painter.fillColor = colors[k++];
painter.BeginPath();
painter.MoveTo(new Vector2(m_Radius, m_Radius));
painter.Arc(new Vector2(m_Radius, m_Radius), m_Radius, angle, anglePct);
painter.Fill();
angle = anglePct;
}
}
}
Editor 的文件夹来存储文件。Editor 文件夹中,创建一个名为 PieChartWindow.cs 的 C# 脚本,其中包含以下内容:using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
public class PieChartWindow : EditorWindow
{
[MenuItem("Tools/PieChart Window")]
public static void ShowExample()
{
PieChartWindow wnd = GetWindow<PieChartWindow>();
wnd.titleContent = new GUIContent("PieChartWindow");
}
public void CreateGUI()
{
VisualElement root = rootVisualElement;
root.Add(new PieChart());
}
}
要在编辑器窗口中查看饼图,请从菜单中选择工具 (Tools) > 饼图窗口 (PieChart Window)。
在 SampleScene 中的 UIDocument 游戏对象中添加饼图。为此,首先,在 pie-chart 文件夹 PieChartComponet.cs 中创建一个名为 C# 的脚本,其中包含以下内容:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
[RequireComponent(typeof(UIDocument))]
public class PieChartComponent : MonoBehaviour
{
PieChart m_PieChart;
void Start()
{
m_PieChart = new PieChart();
GetComponent<UIDocument>().rootVisualElement.Add(m_PieChart);
}
}
要在运行时查看饼图,请执行以下操作: