我有一个纹理,我用它作为屏幕截图。 当我将纹理保存为png文件时,它似乎很完美,但我还想在屏幕上显示捕获的图像。所以我将纹理转换为精灵但由于某种原因,最终结果精灵只是我在屏幕上的另一个UI图像的随机图像,而不是我保存到正确的png文件的纹理。
这是我的代码:
var tex = new Texture2D(recwidth, recheight, TextureFormat.RGB24, false);
Rect rex = new Rect(startX, startY, (float)recwidth, (float)recheight);
WaitForEndOfFrame frameEnd = new WaitForEndOfFrame();
tex.ReadPixels(rex, rdPXX, rdPXY);
tex.Apply();
// Encode texture into PNG
var bytes = tex.EncodeToPNG();
Sprite sprite = new Sprite();
sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width / 2, tex.height / 2));
image.GetComponent<Image>().overrideSprite = sprite;
Destroy(tex);
答案 0 :(得分:2)
不要破坏纹理。 Sprite始终需要纹理参考。 Sprite对象仅保留有关纹理的元数据,如枢轴或UV(精灵地图集中的位置和大小)
答案 1 :(得分:0)
只需使用带有参数的Sprite.Create()直接创建精灵即可。现在,Unity是Create()的默认构造函数。也不要破坏纹理。
尝试一下,
var tex = new Texture2D(recwidth, recheight, TextureFormat.RGB24, false);
Rect rex = new Rect(startX, startY, (float)recwidth, (float)recheight);
WaitForEndOfFrame frameEnd = new WaitForEndOfFrame();
tex.ReadPixels(rex, rdPXX, rdPXY);
tex.Apply();
// Encode texture into PNG
var bytes = tex.EncodeToPNG();
Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width / 2, tex.height / 2));
image.GetComponent<Image>().overrideSprite = sprite;