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截取的都是整個屏幕,相當(dāng)于手機的截屏,無法自定義截圖區(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# 中的委托與事件實現(xiàn)靈活的回調(diào)機制(應(yīng)用場景分析)
委托提供了一種類型安全的方式將方法作為參數(shù)傳遞,而事件則允許對象通知其他對象發(fā)生了某些事情,這篇文章主要介紹了C# 中的委托與事件實現(xiàn)靈活的回調(diào)機制,需要的朋友可以參考下2024-12-12
DevExpress中GridControl列轉(zhuǎn)義的實現(xiàn)方法
這篇文章主要介紹了DevExpress中GridControl列轉(zhuǎn)義的實現(xiàn)方法,在項目開發(fā)中有一定的實用價值,需要的朋友可以參考下2014-08-08
將c#編寫的程序打包成應(yīng)用程序的實現(xiàn)步驟分享(安裝,卸載) 圖文
時常會寫用c#一些程序,但如何將他們和photoshop一樣的大型軟件打成一個壓縮包,以便于發(fā)布.2011-12-12
C#/VB.NET實現(xiàn)在PDF文檔中創(chuàng)建表格
表格是一種直觀高效的數(shù)據(jù)展示方式,可以按行和列的形式呈現(xiàn)數(shù)據(jù),從而更容易吸引讀者的注意,本文將介紹如何使用 Spire.PDF for .NET 通過 .NET 程序在 PDF 文檔中創(chuàng)建表格,需要的可以參考下2023-12-12

