1. 程式人生 > 程式設計 >Unity實現截圖功能

Unity實現截圖功能

本文例項為大家分享了Unity實現截圖功能的具體程式碼,供大家參考,具體內容如下

一、使用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;
    }
  }
}

經過測試,使用ScreenCapture.CaptureScreenshotAsTexture和ScreenCapture.CaptureScreenshotAsTexture擷取的都是整個螢幕,相當於手機的截圖,無法自定義截圖區域,作用不大。使用ScreenCapture.CaptureScreenshot會有延遲。

二、通過Texture2D.ReadPixels來讀取螢幕區域畫素

using UnityEngine;
using System.Collections;
using System;
 
public class ScreenShotTest : MonoBehaviour
{
  private void Update()
  {
    if (Input.GetKeyDown(KeyCode.A))
    {
      StartCoroutine(CaptureByRect());
    }
  }
 
  private IEnumerator CaptureByRect()
  {
    //等待渲染執行緒結束
    yield return new WaitForEndOfFrame();
    //初始化Texture2D,大小可以根據需求更改
    Texture2D mTexture = new Texture2D(Screen.width,Screen.height,TextureFormat.RGB24,false);
    //讀取螢幕畫素資訊並存儲為紋理資料
    mTexture.ReadPixels(new Rect(0,Screen.width,Screen.height),0);
    //應用
    mTexture.Apply();
    //將圖片資訊編碼為位元組資訊
    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();
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。