从任意文件目录下读取文件并在unity中显示:
1)读取目标文件
byte[] imageByte = File.ReadAllBytes(imagePath);
2)转换成纹理
texture.LoadImage(imageByte);
3)转换成精灵
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
4)给image赋值
image.sprite = sprite;
如果图片较大,速度转换会相应变慢,可以考虑吧image换成RawImage,然后通过rawImage.texture = texture直接赋值,省略第三步
全代码
public void SetImageTexture2D( string imagePath, RawImage image) { Stopwatch sw = new Stopwatch(); sw.Start(); byte[] imageByte = File.ReadAllBytes(imagePath); Texture2D texture = new Texture2D(1, 1); texture.LoadImage(imageByte); image.texture = texture; sw.Stop(); print(sw.ElapsedMilliseconds); //Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0)); //image.sprite = sprite; }