【常用】截取相机图片截图功能
生活随笔
收集整理的這篇文章主要介紹了
【常用】截取相机图片截图功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class ScreenShot : MonoBehaviour
{public Camera mainCamera;public Camera uiCamera;/// <summary> /// 對相機截圖。 /// </summary> /// <returns>The screenshot2.</returns> /// <param name="camera">Camera.要被截屏的相機</param> /// <param name="rect">Rect.截屏的區域</param> public Texture2D CaptureCamera(Camera camera, Rect rect){// 創建一個RenderTexture對象 RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, -1);// 臨時設置相關相機的targetTexture為rt, 并手動渲染相關相機 camera.targetTexture = rt;camera.Render();//ps: --- 如果這樣加上第二個相機,可以實現只截圖某幾個指定的相機一起看到的圖像。 //camera2.targetTexture = rt;//camera2.Render();//ps: ------------------------------------------------------------------- // 激活這個rt, 并從中中讀取像素。 RenderTexture.active = rt;Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);screenShot.ReadPixels(rect, 0, 0);// 注:這個時候,它是從RenderTexture.active中讀取像素 screenShot.Apply();// 重置相關參數,以使用camera繼續在屏幕上顯示 camera.targetTexture = null;//camera2.targetTexture = null;RenderTexture.active = null; // JC: added to avoid errors GameObject.Destroy(rt);// 最后將這些紋理數據,成一個png圖片文件 byte[] bytes = screenShot.EncodeToPNG();//存放string filename = Application.streamingAssetsPath + "/Screenshot.png";System.IO.File.WriteAllBytes(filename, bytes);Debug.Log(string.Format("截屏了一張照片: {0}", filename));return screenShot;}public void ScreenST(){CaptureCamera(mainCamera, new Rect(0, 0, Screen.width, Screen.height));}
}
?
總結
以上是生活随笔為你收集整理的【常用】截取相机图片截图功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【常用】鼠标拖动物体移动
- 下一篇: 【常用】单例