当前位置: 首页 > news >正文

Unity:使用Texture2D动态创建的图像无法正常显示 / 修改图像后未生效

开发中遇到需要动态绘制图像的需求,前后文代码如下所示:

Texture2D newImageTexture = new Texture2D(width, height);
Color32[] newImagePixels = new Color32[height * width];for (int y = 0; y < height ; ++y)
{for (int x = 0; x < width; ++x){if (...){newImagePixels[y * width + x] = new Color32(0, 0, 0, 0);}else{if (...){newImagePixels[y * width + x] = new Color32(255, 0, 0, 255);}else{newImagePixels[y * width + x] = new Color32(255, 255, 255, 255);}}}
}newImageTexture.SetPixels32(newImagePixels);
Sprite sprite = Sprite.Create(newImageTexture, new Rect(0.0f, 0.0f, width, height), new Vector2(0.5f, 0.5f));gameObject.GetComponent<Image>().sprite = sprite;

但是经过测试,图像并没有被正常显示出来。经过查阅官方文档,调用SetPixels32后必须调用Apply函数把修改上传到显卡中才能生效(参考链接),因此正确代码如下:

Texture2D newImageTexture = new Texture2D(width, height);
Color32[] newImagePixels = new Color32[height * width];for (int y = 0; y < height ; ++y)
{for (int x = 0; x < width; ++x){if (...){newImagePixels[y * width + x] = new Color32(0, 0, 0, 0);}else{if (...){newImagePixels[y * width + x] = new Color32(255, 0, 0, 255);}else{newImagePixels[y * width + x] = new Color32(255, 255, 255, 255);}}}
}newImageTexture.SetPixels32(newImagePixels);
//加入这句
newImageTexture.Apply(false);
//
Sprite sprite = Sprite.Create(newImageTexture, new Rect(0.0f, 0.0f, width, height), new Vector2(0.5f, 0.5f));gameObject.GetComponent<Image>().sprite = sprite;

另外,经过测试,这样创建的Sprite有时候会莫名其妙灰蒙蒙的,像是被遮罩了。经过测试,加上Instantiate可以解决,但原因未知:

gameObject.GetComponent<Image>().sprite = Instantiate(sprite);
http://www.lryc.cn/news/382788.html

相关文章:

  • 【LinuxC语言】详解TCP/IP
  • 数字化转型下的企业人力资源信息系统研究
  • docker camunda 8.5 部署步骤
  • 学懂C#编程:常用高级技术——委托(Delegate)应用场景——委托与Lambda表达式的结合使用详解
  • 05-java基础——循环习题
  • 网络安全等级保护测评
  • 真有被这套零售数据分析方案惊艳到
  • 亚马逊卖家为何需要自养账号?揭秘背后的原因
  • 牛了,LSTM+Transformer王炸结合创新,荣登Nature,精度高达95.65%
  • Java面试题:通过实例说明工厂模式和抽象工厂模式的用法,以及它们在解耦中的作用
  • 成都欣丰洪泰文化传媒有限公司电商服务的创新者
  • 学习笔记——动态路由——RIP(距离矢量协议)
  • 【python】OpenCV—Segmentation
  • python-题库篇-Python语言特性
  • WEB界面上使用ChatGPT
  • 【Matlab】CNN-LSTM分类 卷积神经网络-长短期记忆神经网络组合模型(附代码)
  • 性能工具之 MySQL OLTP Sysbench BenchMark 测试示例
  • 【QT】QCustomPlot库中iSelectPlottables的使用
  • 字节跳动联手博通:5nm AI芯片诞生了?
  • 【数据结构与算法】动态查找表(二叉排序树,二叉平衡树)详解
  • PyTorch中“No module named ‘torch._six‘“的报错场景及处理方法
  • Spring Boot 集成 MinIO 实现文件上传
  • 目标跟踪——KCF源码用python实现
  • 前端 转换笔记
  • 个人开发笔记
  • pdf压缩,pdf压缩在线,pdf文件太大怎么变小
  • Go 如何使用指针灵活操作内存
  • 【面试干货】Java中的++操作符与线程安全性
  • NLP学习与踩坑记录(持续更新版)
  • Java也能做OCR!SpringBoot 整合 Tess4J 实现图片文字识别