运用Unity制作一个渐变热力图效果

一、同事今天要用到一个热力图效果的风速图,让我试试,然后就做出来了。

  先讲一下大概思路。

  首先是有一个相关数据导入读取的操作,然后利用这些大量的数据计算得出具体的值,最后用一个函数将计算结果赋予到新建的图像纹理贴图上。

二、操作步骤

首先构建好对应的初始变量:rawimage 、贴图大小、存储数据(这里用的是风场数据,构建的风场数据渐变效果)的二维列表。

public RawImage heatmapImage;
    public int textureWidth = 256;
    public int textureHeight = 256;
    public WindDataVisualizer windDataVisualizer;

    private Texture2D heatmapTexture;
    private List<List<float>> windSpeedData = new List<List<float>>();

接着再在start函数内部将图的相关参数初始化一下,当然尺寸参数公开化了,所以在外部自己设也没关系。

void Start()
    {
        InitializeHeatmap();
    }

    private void InitializeHeatmap()
    {
        if (heatmapImage == null)
        {
            Debug.LogError("Heatmap RawImage not assigned!");
            return;
        }

        // 创建并初始化纹理
        heatmapTexture = new Texture2D(textureWidth, textureHeight);
        heatmapTexture.filterMode = FilterMode.Bilinear;
        heatmapImage.texture = heatmapTexture;

        // 初始化为黑色
        Color[] colors = new Color[textureWidth * textureHeight];
        for (int i = 0; i < colors.Length; i++)
        {
            colors[i] = Color.black;
        }
        heatmapTexture.SetPixels(colors);
        heatmapTexture.Apply();
    }

然后就是对于数据的读取和初始化以及对应数据点位在图像位置的映射操作,这一部分由于是内部数据不方便公开。

最后就是创建颜色的渐变效果了。

在这一块上,我们还是采用梯度分级的方法做颜色映射,再用lerp()函数平滑过渡进而造成一种渐变效果。

private Color GetWindColor(float windSpeed)
    {
        if (windDataVisualizer == null)
            return Color.black;

        float maxSpeed = windDataVisualizer.maxWindSpeed;
        if (maxSpeed <= 0)
            return Color.black;

        float normalizedSpeed = Mathf.Clamp01(windSpeed / maxSpeed);

        // 创建颜色渐变
        if (normalizedSpeed < 0.2f)
            return Color.Lerp(Color.blue, Color.cyan, normalizedSpeed * 5f);
        else if (normalizedSpeed < 0.4f)
            return Color.Lerp(Color.cyan, Color.green, (normalizedSpeed - 0.2f) * 5f);
        else if (normalizedSpeed < 0.6f)
            return Color.Lerp(Color.green, Color.yellow, (normalizedSpeed - 0.4f) * 5f);
        else if (normalizedSpeed < 0.8f)
            return Color.Lerp(Color.yellow, Color.red, (normalizedSpeed - 0.6f) * 5f);
        else
            return Color.Lerp(Color.red, Color.magenta, (normalizedSpeed - 0.8f) * 5f);
    }

三、效果展示

可以看见底部的渐变图效果就是我们的成果啦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值