【常用】截取相机图片截图功能
生活随笔
收集整理的這篇文章主要介紹了
【常用】截取相机图片截图功能
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class ScreenShot : MonoBehaviour
{public Camera mainCamera;public Camera uiCamera;/// <summary> /// 對相機(jī)截圖。 /// </summary> /// <returns>The screenshot2.</returns> /// <param name="camera">Camera.要被截屏的相機(jī)</param> /// <param name="rect">Rect.截屏的區(qū)域</param> public Texture2D CaptureCamera(Camera camera, Rect rect){// 創(chuàng)建一個RenderTexture對象 RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, -1);// 臨時設(shè)置相關(guān)相機(jī)的targetTexture為rt, 并手動渲染相關(guān)相機(jī) camera.targetTexture = rt;camera.Render();//ps: --- 如果這樣加上第二個相機(jī),可以實現(xiàn)只截圖某幾個指定的相機(jī)一起看到的圖像。 //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();// 重置相關(guān)參數(shù),以使用camera繼續(xù)在屏幕上顯示 camera.targetTexture = null;//camera2.targetTexture = null;RenderTexture.active = null; // JC: added to avoid errors GameObject.Destroy(rt);// 最后將這些紋理數(shù)據(jù),成一個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));}
}
?
總結(jié)
以上是生活随笔為你收集整理的【常用】截取相机图片截图功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【常用】鼠标拖动物体移动
- 下一篇: 【常用】单例