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

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

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部