unity 截圖
阿新 • • 發佈:2018-12-16
= =找不到難點拿出來說,直接看程式碼吧
using UnityEngine; using System.Collections; using System; public static class Screenshot { #region 全屏截圖 public static IEnumerator CaptureScreen(string savaPath) { return CaptureScreen(new Rect(0, 0, Screen.width, Screen.height), savaPath); } public static IEnumerator CaptureScreen(Action<Texture2D> callback) { return CaptureScreen(new Rect(0, 0, Screen.width, Screen.height), callback); } public static void CaptureScreen(Camera camera, string savaPath) { CaptureScreen(camera,new Rect(0, 0, Screen.width, Screen.height), savaPath); } public static void CaptureScreen(Camera camera, Action<Texture2D> callback) { CaptureScreen(camera,new Rect(0, 0, Screen.width, Screen.height), callback); } #endregion /// <summary> /// 截圖指定區域,包括該區域所有物件 /// </summary> /// <param name="rect"></param> /// <param name="savaPath"></param> /// <returns></returns> public static IEnumerator CaptureScreen(Rect rect, string savaPath) { yield return new WaitForEndOfFrame(); Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false); screenShot.ReadPixels(rect, 0, 0, false); screenShot.Apply(); byte[] bytes = screenShot.EncodeToPNG(); System.IO.File.WriteAllBytes(savaPath, bytes); Texture2D.Destroy(screenShot); bytes = null; } public static IEnumerator CaptureScreen(Rect rect, Action<Texture2D> callback) { yield return new WaitForEndOfFrame(); Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false); screenShot.ReadPixels(rect, 0, 0, false); screenShot.Apply(); callback(screenShot); } /// <summary> /// 截圖指定相機的指定區域,只會獲得該相機的畫素[不包括相機的渲染] /// </summary> /// <param name="c"></param> /// <param name="r"></param> /// <param name="savePath"></param> public static void CaptureScreen(Camera c, Rect r, string savePath) { RenderTexture rt = new RenderTexture((int)r.width, (int)r.height, 0); c.targetTexture = rt; c.Render(); RenderTexture.active = rt; Texture2D screenShot = new Texture2D((int)r.width, (int)r.height, TextureFormat.RGB24, false); screenShot.ReadPixels(r, 0, 0); screenShot.Apply(); c.targetTexture = null; RenderTexture.active = null; GameObject.Destroy(rt); byte[] bytes = screenShot.EncodeToPNG(); System.IO.File.WriteAllBytes(savePath, bytes); GameObject.Destroy(screenShot); } public static void CaptureScreen(Camera c, Rect r, Action<Texture2D> callback) { RenderTexture rt = new RenderTexture((int)r.width, (int)r.height, 0); c.targetTexture = rt; c.Render(); RenderTexture.active = rt; Texture2D screenShot = new Texture2D((int)r.width, (int)r.height, TextureFormat.RGB24, false); screenShot.ReadPixels(r, 0, 0); screenShot.Apply(); c.targetTexture = null; RenderTexture.active = null; GameObject.Destroy(rt); callback(screenShot); } }