Unity RawImage和Image的区别
一、相同点
RawImage和Image都是可以用于显示图片的组件
二、区别
2.1区别
Image 组件主要用于显示 Sprite 或其他常见格式的 2D 图像,
而 RawImage 则更适用于显示未经处理的Texture2D纹理或使用特殊格式的纹理。
2.2 RawImage的优势
RawImage可以直接使用Texture2D,而Image使用Sprite
接下来演示代码
//从图片的路径读取bytes字节流
byte[] bytes = File.ReadAllBytes(photoPath);
//byte[] 转 Texture2D
Texture2D tex = new Texture2D(1, 1);
tex.LoadImage(bytes);
//可以直接把Texture2D 赋给 RawImage
rawImage.texture = tex;
// Texture2D 转 Sprite
Sprite sp = Sprite.Create(tex , new Rect(0, 0, tex.width, tex.height), Vector2.zero);
//把Sprite赋给image
image.sprite = sp;
可以看到从一个文件路径出发,到显示到图片组件,Image比RawImage多了一步Sprite.Create()转化操作,而这一步在图片比较大,比如4M或以上,是可以明显感到耗时,大概耗时会1秒以上,看机器。所以这种需求可以选择RawImage
2.3 Image的优势
Image则支持缩放、拉伸、旋转等高级显示效果。也有preserveAspect属性,可以按比例显示。而使用RawImage,就得根据Texture2D的宽高比,自己计算比例了
三、颜色空间转换
有时,我们想借用RenderTexture把相机的画面转成图片,如下图
//把画面转到Texture2D t;
Camera camera = self.avatarCameraGo.GetComponent<Camera>();
RenderTexture.active = camera.targetTexture;
var width = camera.targetTexture.width;
var height = camera.targetTexture.height;
Texture2D t = new Texture2D(width, height,TextureFormat.RGBA32,false);
t.ReadPixels(new Rect(0, 0, width, height), 0, 0);
t.Apply();
RenderTexture.active = null;
如果直接显示,那么有可能显示出后,图片黑黑的,和原图不一样。如下图
但是原图是这样的
这时我们需要对Texture2D进行颜色空间转换,如下图。转换颜色空间就好了
var newTex = t;
if (QualitySettings.activeColorSpace == ColorSpace.Linear)
{
newTex = self.LinearToGammaSpace(t);
}
/// <summary>
/// linear颜色空间转换到gamma颜色空间
/// </summary>
private static Texture2D LinearToGammaSpace(this DlgCreCharacNew self,Texture2D texture)
{
Texture2D result = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
Color[] pixels = texture.GetPixels();
for (int i = 0; i < pixels.Length; i++)
{
Color color = pixels[i];
color.r = Mathf.LinearToGammaSpace(color.r);
color.g = Mathf.LinearToGammaSpace(color.g);
color.b = Mathf.LinearToGammaSpace(color.b);
color.a = Mathf.LinearToGammaSpace(color.a);
pixels[i] = color;
}
result.SetPixels(pixels);
result.Apply();
return result;
}