本文已参与[新人创作礼]活动,一起开启掘金创作之路。
本文将告诉大家怎么实现unity里面的截图功能。实际就是截取虚拟相机的画面。
需要新建个摄像机,避免原来的摄像机被占走。废话不多说,直接上代码:
// 截图
RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 16);
mainCamera.targetTexture = rt;
mainCamera.Render();
RenderTexture.active = rt;
Texture2D t = new Texture2D(Screen.width, Screen.height);
t.ReadPixels(new Rect(0, 0, t.width, t.height), 0, 0);
t.Apply();
byte[] pngBytes = t.EncodeToPNG();
Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(pngBytes);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
imagePreviewer.sprite = sprite;
System.IO.File.WriteAllBytes(Application.dataPath + "//mainScene.jpg", pngBytes);
Debug.Log("!!!");
imagePreviewer是图片的预览器,最后还把图片写到了本地,用的就是 System.IO.File.WriteAllBytes(Application.dataPath + "//mainScene.jpg", pngBytes); 这一句。