//获取当前屏幕截图的字符串
private string GetScreenShotBase64()
{
LoadingUI.instance.SetValueAndContent(0f, true);
Rect camPixelRect = mainCamera.pixelRect;
// 创建一个RenderTexture对象
RenderTexture rt = new RenderTexture((int)camPixelRect.width, (int)camPixelRect.height,0);
Rect rect = new Rect(0, 0, camPixelRect.width, camPixelRect.height);
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
mainCamera.enabled = false;
mainCamera.targetTexture = rt;
//mainCamera.Render();
mainCamera.clearFlags = CameraClearFlags.SolidColor;
mainCamera.renderingPath = RenderingPath.DeferredLighting;
mainCamera.Render();
mainCamera.clearFlags = CameraClearFlags.Skybox;
mainCamera.renderingPath = RenderingPath.Forward;
// 激活这个rt, 并从中中读取像素。
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)camPixelRect.width, (int)camPixelRect.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.Apply();
byte[] bytes = CommonFunction.ZipTexture2D(screenShot, rect);
string photoBase64 = Convert.ToBase64String(bytes);
LoadingUI.instance.SetValueAndContent(0.6f, true);
// 重置相关参数,以使用camera继续在屏幕上显示
mainCamera.targetTexture = null;
mainCamera.enabled = true;
RenderTexture.active = null; // JC: added to avoid errors
GameObject.Destroy(rt);
// 最后将这些纹理数据,成一个png图片文件
//byte[] bytes = screenShot.EncodeToPNG();
string filename = Application.dataPath + "/BomScreenshot.png";
#if UNITY_WEBPLAYER
Debug.Log(filename);
#elif UNITY_STANDALONE_WIN
System.IO.File.WriteAllBytes(filename, bytes);
Debug.Log(string.Format("截屏了一张照片: {0}", filename));
#endif
LoadingUI.instance.SetValueAndContent(1f, false);
return photoBase64;
}
//将截图保存,压缩至1.8M以下
public static byte[] ZipTexture2D(Texture2D screenShot, Rect capture)
{
GC.Collect();
GC.WaitForPendingFinalizers();
long start = GC.GetTotalMemory(true);
byte[] bytes = screenShot.EncodeToPNG();
GC.Collect();
GC.WaitForPendingFinalizers();
long end = GC.GetTotalMemory(true);
if ((end - start) >= 1887436)//所占内存是否大于1.8M
{
screenShot.Resize((int)(screenShot.width * 0.9f), (int)(screenShot.height * 0.9f), TextureFormat.RGB24, false);
screenShot.ReadPixels(capture, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.Apply();
return ZipTexture2D(screenShot, capture);
}
return bytes;
}