Unity中动态生成贴图并保存成png图片实现

实现原理:

要生成长x宽y的贴图,就是生成x*y个像素填充到贴图中,如下图:

如果要改变局部颜色,就是从x1到x2(x1<x2),y1到y2(y1<y2)这个范围做处理,

或者要想做圆形就是计算距某个点(x1,y1)在一定长度d的范围内做处理

代码:

cs 复制代码
    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);

最终就会在文件夹中保存了图片

相关推荐
℡枫叶℡7 小时前
Unity - 全局配置Unity工程的资源检索的目录
unity·资源检索配置
mxwin8 小时前
Unity URP 下 TBN 矩阵学习 切线空间、tangent.w 与镜像 UV 的那些坑
学习·unity·矩阵·shader
程序猿多布8 小时前
Unity导表工具解决方案-Luban使用教程
unity·luban
mxwin8 小时前
Unity URP Shader 混合模式完全指南
unity·游戏引擎
mxwin8 小时前
Unity URP 下 HDR 与 Tonemapping 的 Shader 意识
unity·游戏引擎
沉默金鱼9 小时前
U3D高级编程:主程手记——第二章2.1读书笔记
unity·游戏引擎
mxwin20 小时前
Unity Shader 深度写入与关闭ZWrite Off · 半透明排序 · 粒子穿插
unity·游戏引擎·shader
张老师带你学21 小时前
宇宙飞船完整Unity项目
科技·游戏·unity·游戏引擎·模型
mxwin1 天前
Unity URP 下的流体模拟 深入解析 Navier-Stokes 方程与浅水方程的数学原理
unity·游戏引擎
mxwin1 天前
Unity Shader 深度重建世界坐标
unity·游戏引擎·shader