使用unity项目开发过程中需要用到系统截图功能时,其实主要的做法是将RenderTexture转换为Texture2D,然后再转为byte数组,最后创建图片文件,写入内存。下面是代码演示:
public static bool SaveRenderTextureToPNG(RenderTexture rt, string contents, string pngName)
{
Debug.Log("正在保存PNG图片...." + contents + "....." + pngName);
RenderTexture prev = RenderTexture.active;
RenderTexture.active = rt;
Texture2D png = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
png.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
byte[] bytes = png.EncodeToPNG();
// if (!Directory.Exists(contents))
// Directory.CreateDirectory(contents);
string path = Path.Combine(Application.dataPath, pngName + ".jpeg");
FileStream file = File.Open(path, FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
Texture2D.DestroyImmediate(png);
png = null;
RenderTexture.active = prev;
return true;
}
}