Unity實現(xiàn)截圖功能
更新時間:2020年04月16日 14:33:56 作者:LLLLL__
這篇文章主要為大家詳細介紹了Unity實現(xiàn)截圖功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Unity實現(xiàn)截圖功能的具體代碼,供大家參考,具體內(nèi)容如下
一、使用Unity自帶API
using UnityEngine; using UnityEngine.UI; public class ScreenShotTest : MonoBehaviour { public RawImage img; private void Update() { //使用ScreenCapture.CaptureScreenshot if (Input.GetKeyDown(KeyCode.A)) { ScreenCapture.CaptureScreenshot(Application.dataPath + "/Resources/Screenshot.jpg"); img.texture = Resources.Load<Texture>("Screenshot"); } //使用ScreenCapture.CaptureScreenshotAsTexture if (Input.GetKeyDown(KeyCode.S)) { img.texture = ScreenCapture.CaptureScreenshotAsTexture(0); } //使用ScreenCapture.CaptureScreenshotAsTexture if (Input.GetKeyDown(KeyCode.D)) { RenderTexture renderTexture = new RenderTexture(720, 1280, 0); ScreenCapture.CaptureScreenshotIntoRenderTexture(renderTexture); img.texture = renderTexture; } } }
經(jīng)過測試,使用ScreenCapture.CaptureScreenshotAsTexture和ScreenCapture.CaptureScreenshotAsTexture截取的都是整個屏幕,相當于手機的截屏,無法自定義截圖區(qū)域,作用不大。使用ScreenCapture.CaptureScreenshot會有延遲。
二、通過Texture2D.ReadPixels來讀取屏幕區(qū)域像素
using UnityEngine; using System.Collections; using System; public class ScreenShotTest : MonoBehaviour { private void Update() { if (Input.GetKeyDown(KeyCode.A)) { StartCoroutine(CaptureByRect()); } } private IEnumerator CaptureByRect() { //等待渲染線程結(jié)束 yield return new WaitForEndOfFrame(); //初始化Texture2D, 大小可以根據(jù)需求更改 Texture2D mTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); //讀取屏幕像素信息并存儲為紋理數(shù)據(jù) mTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); //應(yīng)用 mTexture.Apply(); //將圖片信息編碼為字節(jié)信息 byte[] bytes = mTexture.EncodeToPNG(); //保存(不能保存為png格式) string fileName = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + ".jpg"; System.IO.File.WriteAllBytes(Application.streamingAssetsPath + "/ScreenShot/" + fileName, bytes); UnityEditor.AssetDatabase.Refresh(); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#(.Net)將非托管dll嵌入exe中的實現(xiàn)
本文主要介紹了C#(.Net)將非托管dll嵌入exe中的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12