一、同事今天要用到一个热力图效果的风速图,让我试试,然后就做出来了。
先讲一下大概思路。
首先是有一个相关数据导入读取的操作,然后利用这些大量的数据计算得出具体的值,最后用一个函数将计算结果赋予到新建的图像纹理贴图上。
二、操作步骤
首先构建好对应的初始变量: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);
}
三、效果展示
可以看见底部的渐变图效果就是我们的成果啦!