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

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

相关推荐
wgslucky6 小时前
Godot GDScript初学者遇到的问题记录
游戏引擎·godot
点心的游戏开发世界8 小时前
GDScript 入门笔记(五):函数
笔记·游戏引擎·godot
谢斯11 小时前
[unity]如何在unity中添加newtonsoft-json
unity·json·游戏引擎
天人合一peng12 小时前
Unity标记固定颜色及投影标记
unity
云雨巫山15 小时前
Unity 游戏开发性能优化全景手册
unity·智能手机·性能优化·游戏引擎
maybeyaluokenai15 小时前
unity build in渲染管线概述
unity·图形渲染
学习星球15 小时前
AI 原生游戏开发:Godot 4 + AI Agent 全栈指南(Ziva 3 / Godot MCP 深度实战)
人工智能·游戏引擎·godot
云雨巫山15 小时前
Unity 性能优化 · 图解全景手册
unity·性能优化·游戏引擎
Madokaly1 天前
DOTween的Vector3Plugin
unity
Rina GO2 天前
PS怎么把文字贴在圆柱体上?2种实用方法教程附不规则物体贴图
人工智能·贴图·ps插件·不规则物体贴图·文字贴图·ai贴图