先看效果:
直接上代码:
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
public class SolidAttributeGraph : MonoBehaviour
{
private Texture2D texture;
private int width = 256;
private int height = 256;
public float[] pos = new float[5];
void Start()
{
texture = new Texture2D(width, height);
DrawGraph(pos);
this.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, width, height), new Vector2(0.5f, 0.5f), 100.0f);
}
public void Relines()
{
DrawGraph(pos);
}
private void DrawGraph(float[] attributes)
{
List<Vector2> points = new List<Vector2>();
float angleStep = 360f / attributes.Length;
float startingAngle = 90f;
float radius = Mathf.Min(width, height) / 2f * 0.8f;
Vector2 center = new Vector2(width / 2, height / 2);
for (int i = 0; i < attributes.Length; i++)
{
float normalizedAttribute = Mathf.Clamp(attributes[i], 0, 1);
float angle = (startingAngle - i * angleStep) * Mathf.Deg2Rad;
points.Add(center + new Vector2(Mathf.Cos(angle) * radius * normalizedAttribute, Mathf.Sin(angle) * radius * normalizedAttribute));
}
FillPolygon(points);
texture.Apply();
}
private void FillPolygon(List<Vector2> points)
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
texture.SetPixel(x, y, Color.clear);
}
}
for (int y = 0; y < height; y++)
{
List<int> nodeX = new List<int>();
int j = points.Count - 1;
for (int i = 0; i < points.Count; i++)
{
if (points[i].y < y && points[j].y >= y || points[j].y < y && points[i].y >= y)
{
nodeX.Add((int)(points[i].x + (y - points[i].y) / (points[j].y - points[i].y) * (points[j].x - points[i].x)));
}
j = i;
}
if (nodeX.Count > 1)
{
nodeX.Sort();
}
for (int i = 0; i < nodeX.Count; i += 2)
{
if (nodeX[i] >= width) break;
if (nodeX[i + 1] > 0)
{
if (nodeX[i] < 0) nodeX[i] = 0;
if (nodeX[i + 1] > width) nodeX[i + 1] = width;
for (int x = nodeX[i]; x < nodeX[i + 1]; x++)
texture.SetPixel(x, y, Color.red);
}
}
}
}
}
新建一个image,将脚本放上即可
背景图自己找一个就行!