Unity实现属性雷达图

先看效果:

直接上代码:

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,将脚本放上即可

背景图自己找一个就行!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值