Unity 通過攝像機截圖並把圖篇儲存
阿新 • • 發佈:2021-03-28
【CSND】Unity遊戲開發學習群
加入我們一起學習吧:1022366216
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScreenShot : MonoBehaviour {
public Camera targetCamera;
void Update()
{
//滑鼠右鍵按下,進行三種截圖方式的呼叫
if (Input.GetMouseButtonDown(0))
{
ScreenShot_ScreenCapture ();
StartCoroutine(ScreenShot_ReadPixels());
targetCamera.gameObject.SetActive(true);
ScreenShot_ReadPixelsWithCamera(targetCamera);
targetCamera.gameObject.SetActive(false);
//重新整理工程目錄,顯示儲存的圖片,這裡可以不要,改為手動即可
//AssetDatabase.Refresh ();
}
}
//Unity自帶的截圖功能
private void ScreenShot_ScreenCapture()
{
//截圖並儲存
ScreenCapture.CaptureScreenshot(Application.dataPath + "/ScreenShot_ScreenCapture.png");
}
//讀取螢幕畫素進行截圖
private IEnumerator ScreenShot_ReadPixels()
{
yield return new WaitForEndOfFrame();
//讀取畫素
Texture2D tex = new Texture2D(Screen.width, Screen.height);
tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
tex.Apply();
//儲存讀取的結果
string path = Application.dataPath + "/ScreenShot_ReadPixels.png";
System.IO.File.WriteAllBytes(path, tex.EncodeToPNG());
}
//讀取指定相機渲染的畫素
private void ScreenShot_ReadPixelsWithCamera(Camera _camera)
{
//對指定相機進行 RenderTexture
RenderTexture renTex = new RenderTexture(Screen.width, Screen.height, 16);
_camera.targetTexture = renTex;
_camera.Render();
RenderTexture.active = renTex;
//讀取畫素
Texture2D tex = new Texture2D(Screen.width, Screen.height);
tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
tex.Apply();
//讀取目標相機畫素結束,渲染恢復原先的方式
_camera.targetTexture = null;
RenderTexture.active = null;
Destroy(renTex);
//儲存讀取的結果
string path = Application.dataPath + "/ScreenShot_ReadPixelsWithCamera.png";
System.IO.File.WriteAllBytes(path, tex.EncodeToPNG());
}
}