Unity實(shí)現(xiàn)截圖功能
本文實(shí)例為大家分享了Unity實(shí)現(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)過(guò)測(cè)試,使用ScreenCapture.CaptureScreenshotAsTexture和ScreenCapture.CaptureScreenshotAsTexture截取的都是整個(gè)屏幕,相當(dāng)于手機(jī)的截屏,無(wú)法自定義截圖區(qū)域,作用不大。使用ScreenCapture.CaptureScreenshot會(huì)有延遲。
二、通過(guò)Texture2D.ReadPixels來(lái)讀取屏幕區(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); //讀取屏幕像素信息并存儲(chǔ)為紋理數(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(); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#(.Net)將非托管dll嵌入exe中的實(shí)現(xiàn)
本文主要介紹了C#(.Net)將非托管dll嵌入exe中的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12Unity實(shí)現(xiàn)簡(jiǎn)單手勢(shì)識(shí)別
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)簡(jiǎn)單手勢(shì)識(shí)別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07基于C#實(shí)現(xiàn)鼠標(biāo)設(shè)置功能
這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)鼠標(biāo)設(shè)置功能,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12