Unity截圖方法,在Unity中進行截圖。
阿新 • • 發佈:2019-02-01
今天我們討論下Unity3D的截圖方法,總共有三種方式。
1、利用Unity自帶的系統方式進行截圖:
Application.CaptureScreenshot("Screenshot.png");
2、利用Texture2D.ReadPixels()方法和Texture2D.EncodeToPng()方法進行截圖並儲存資料,程式碼如下:
using System.IO;
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Start() {
UploadPNG();
}
//開啟一個攜程進行截圖
IEnumerator UploadPNG()
{
//等待幀結束
yield return new WaitForEndOfFrame();
//獲取到螢幕的寬高,進行全屏截圖
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
//將圖片轉成byte資料
byte[] bytes = tex.EncodeToPNG();
Destroy(tex);
//利用post方法將圖片資料進行上傳
WWWForm form = new WWWForm();
form.AddField("frameCount", Time.frameCount.ToString());
form.AddBinaryData("fileUpload", bytes);
WWW w = new WWW("http://localhost/cgi-bin/env.cgi?post", form);
yield return w;
if (w.error != null)
print(w.error);
else
print("Finished Uploading Screenshot");
}
}
3、針對某個相機進行截圖,程式碼如下所示:
Texture2D CaptureCamera(Camera camera, Rect rect)
{
// 建立一個RenderTexture物件
RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
// 臨時設定相關相機的targetTexture為rt, 並手動渲染相關相機
camera.targetTexture = rt;
camera.Render();
//如果這樣加上第二個相機,可以實現只截圖某幾個指定的相機一起看到的影象。
//camera2.targetTexture = rt;
//camera2.Render();
// 啟用這個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.dataPath + "/Screenshot.png";
System.IO.File.WriteAllBytes(filename, bytes);
Debug.Log(string.Format("截圖了一張照片: {0}", filename));
return screenShot;
}