Unity realizes the function of Screenshot

Time:2020-12-6

In this paper, we share the specific code of unity to achieve the screenshot function for your reference. The specific content is as follows

1、 Using unity’s own API

using UnityEngine;
using UnityEngine.UI;
 
public class ScreenShotTest : MonoBehaviour
{
  public RawImage img;
 
  private void Update()
  {
    //Use ScreenCapture.CaptureScreenshot
    if (Input.GetKeyDown(KeyCode.A))
    {
      ScreenCapture.CaptureScreenshot(Application.dataPath + "/Resources/Screenshot.jpg");
      img.texture = Resources.Load<Texture>("Screenshot");
    }
 
    //Use ScreenCapture.CaptureScreenshotAsTexture
    if (Input.GetKeyDown(KeyCode.S))
    {
      img.texture = ScreenCapture.CaptureScreenshotAsTexture(0);
    }
 
    //Use ScreenCapture.CaptureScreenshotAsTexture
    if (Input.GetKeyDown(KeyCode.D))
    {
      RenderTexture renderTexture = new RenderTexture(720, 1280, 0);
      ScreenCapture.CaptureScreenshotIntoRenderTexture(renderTexture);
      img.texture = renderTexture;
    }
  }
}

After testing, using ScreenCapture.CaptureScreenshotAsTexture and ScreenCapture.CaptureScreenshotAsTexture The screen capture is the whole screen, which is equivalent to the screen capture of the mobile phone. The screenshot area cannot be customized and has little effect. use ScreenCapture.CaptureScreenshot There will be delays.

2、 Read screen area pixels through 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()
  {
    //Wait for the rendering thread to finish
    yield return new WaitForEndOfFrame();
    //Initialize texture2d, and the size can be changed according to your needs
    Texture2D mTexture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
    //Read the screen pixel information and store it as texture data
    mTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
    //Application
    mTexture.Apply();
    //Encode picture information as byte information
    byte[] bytes = mTexture.EncodeToPNG();
    //Save (cannot save in PNG format)
    string fileName = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + ".jpg";
    System.IO.File.WriteAllBytes(Application.streamingAssetsPath + "/ScreenShot/" + fileName, bytes);
 
    UnityEditor.AssetDatabase.Refresh();
  }
}

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.