Unity中动态生成贴图并保存成png图片实现
实现原理:
要生成长x宽y的贴图,就是生成x*y个像素填充到贴图中,如下图:
如果要改变局部颜色,就是从x1到x2(x1<x2),y1到y2(y1<y2)这个范围做处理,
或者要想做圆形就是计算距某个点(x1,y1)在一定长度d的范围内做处理
代码:
Vector3 point;
float d;
Texture2D t = new Texture2D(width,height);
Color[] pixelColors = new Color[width * height];
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
if(Mathf.Abs(i-width/2 - point.x)<d && Mathf.Abs(j-height/2 - point.z)<d){
pixelColors[i * this.height + j] = new Color(0,0,0,0);
}else{
pixelColors[i * height + j] = Color.black;
}
}
}
t.SetPixels(pixelColors);
t.Apply();
byte[] b = t.EncodeToPNG();
System.IO.File.WriteAllBytes(Application.dataPath+"/t.png",b);
最终就会在文件夹中保存了图片