开发中遇到需要动态绘制图像的需求,前后文代码如下所示:
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);
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » Unity:使用Texture2D动态创建的图像无法正常显示 / 修改图像后未生效
发表评论 取消回复