對相機所看的視角截屏保存爲圖片:ide
1 using UnityEngine; 2 using System.Collections; 3 using UnityEngine.UI; 4 /// <summary>
5 /// 對相機截圖 6 /// </summary>
7 public class Jietu : MonoBehaviour { 8
9 public Camera camera; 10 Texture2D tex; 11 void Start() 12 { 13 tex= CaptureCamera(camera,new Rect(0,0,Screen.width,Screen.height)); 14 GameObject.Find("Canvas/Image").GetComponent<Image>().sprite=Sprite.Create(tex, new Rect(0, 0,tex.width,tex.height), new Vector2(0.5f, 0.5f)); 15 } 16 Texture2D CaptureCamera(Camera cam,Rect rect) 17 { 18 //建立一個RenderTexture對象
19 RenderTexture rt=new RenderTexture ((int)rect.width,(int)rect.height,0); 20 //臨時設置相關相機的targetTexture爲rt,並手動渲染相關相機
21 cam.targetTexture=rt; 22 cam.Render(); 23 //ps: --- 若是這樣加上第二個相機,能夠實現只截圖某幾個指定的相機一塊兒看到的圖像。 24 //ps: camera2.targetTexture = rt; 25 //ps: camera2.Render(); 26 //ps: ------------------------------------------------------------------- 27
28 // 激活這個rt, 並從中中讀取像素。
29 RenderTexture.active = rt; 30 Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24,false); 31 screenShot.ReadPixels(rect, 0, 0);// 注:這個時候,它是從RenderTexture.active中讀取像素
32 screenShot.Apply(); 33
34 // 重置相關參數,以使用camera繼續在屏幕上顯示
35 camera.targetTexture = null; 36 //ps: camera2.targetTexture = null;
37 RenderTexture.active = null; // JC: added to avoid errors
38 GameObject.Destroy(rt); 39 // 最後將這些紋理數據,成一個png圖片文件
40 byte[] bytes = screenShot.EncodeToPNG(); 41 string filename = Application.dataPath + "/Screenshot.png"; 42 System.IO.File.WriteAllBytes(filename, bytes); 43 Debug.Log(string.Format("截了一張照片: {0}", filename)); 44 return screenShot; 45 } 46 }
轉載一下,以備後用。spa