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);

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

相关推荐
XR-AI-JK4 小时前
Unity VR/MR开发-VR/开发SDK选型对比分析
unity·vr·mr
心之所向,自强不息11 小时前
【Unity Shader编程】之让画面动起来
unity·游戏引擎
不伤欣1 天前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
Magnum Lehar1 天前
vulkan游戏引擎test文件memory实现
游戏引擎
Magnum Lehar1 天前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
快乐觉主吖2 天前
Unity的日志管理类
android·unity·游戏引擎
WarPigs2 天前
Unity性能优化笔记
笔记·unity·游戏引擎
T.D.C2 天前
【业务框架】3C-相机-Cinemachine
unity
Tiger Z2 天前
R 语言科研绘图第 55 期 --- 网络图-聚类
开发语言·r语言·贴图
一线灵2 天前
跨平台游戏引擎 Axmol-2.6.1 发布
游戏引擎