Unity 캡처 스크린샷 튜토리얼

이번 포스팅에서는 Unity에서 게임 내 스크린샷을 캡처하는 방법을 보여드리겠습니다.

  • 새 스크립트를 만들고 이를 SC_ScreenAPI라고 부르고 그 안에 아래 코드를 붙여넣습니다.

SC_ScreenAPI.cs

using UnityEngine;

public static class SC_ScreenAPI
{
    /// <summary>
    /// </summary>
    /// <param name="limitSize">If above 0, will make sure that the width and height of the captured image are equal or less than specified.</param>
    /// <returns>Returns a Texture2D.</returns>
    public static Texture2D CaptureScreen(int limitSize = 0)
    {
        //Create a texture the size of the screen, RGB24 format
        int width = Screen.width;
        int height = Screen.height;
        Texture2D screenshot = new Texture2D(width, height, TextureFormat.RGB24, false);
        //Read screen contents into the texture
        screenshot.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        screenshot.Apply();

        if (limitSize > 0)
        {
            screenshot = ScaleTexture(screenshot, limitSize);
        }

        return screenshot;
    }

    static Texture2D ScaleTexture(Texture2D source, int limitSize)
    {
        int width = source.width;
        int height = source.height;
        bool resize = false;

        if (limitSize > 0)
        {
            if (width > limitSize || height > limitSize)
            {
                int newWidth = 0;
                int newHeight = 0;

                float tmpRatio = (width * 1.000f) / (height * 1.000f);
                if (tmpRatio == 1)
                {
                    newWidth = limitSize;
                    newHeight = limitSize;
                }
                else
                {
                    if (tmpRatio > 1)
                    {
                        newWidth = limitSize;
                        newHeight = (int)(limitSize / tmpRatio);
                    }
                    else
                    {
                        newWidth = (int)(limitSize * tmpRatio);
                        newHeight = limitSize;
                    }
                }

                width = newWidth;
                height = newHeight;
                if(width > 0 && height > 0)
                {
                    resize = true;
                }
            }
        }

        if (resize)
        {
            Texture2D result = new Texture2D(width, height, source.format, true);
            Color[] rpixels = result.GetPixels(0);
            float incX = (1.0f / (float)width);
            float incY = (1.0f / (float)height);
            for (int px = 0; px < rpixels.Length; px++)
            {
                rpixels[px] = source.GetPixelBilinear(incX * ((float)px % width), incY * ((float)Mathf.Floor(px / width)));
            }
            result.SetPixels(rpixels, 0);
            result.Apply();
            return result;
        }

        return source;
    }
}

사용하는 방법

  • 화면은 Texture2D를 반환하는 SC_ScreenAPI.CaptureScreen();을 호출하여 캡처됩니다.
  • 선택적으로 이미지 크기를 줄이는(너비나 높이가 제한 값보다 큰 경우) LimitSize 값을 제공할 수 있습니다.

참고: SC_ScreenAPI.CaptureScreen() 호출; 오류를 방지하려면 프레임이 끝난 후에 수행해야 하므로 IEnumerator 내부에서 사용하세요.

SC_ScreenCaptureTest.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SC_ScreenCaptureTest : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        //Press Q to capture screenshot
        if (Input.GetKeyDown(KeyCode.Q))
        {
            StartCoroutine(CaptureScreen());
        }
    }

    IEnumerator CaptureScreen()
    {
        yield return new WaitForEndOfFrame();

        //Here is a captured screenshot
        Texture2D screenshot = SC_ScreenAPI.CaptureScreen();

        //And here is how you get a byte array of the screenshot, you can use it to save the image locally, upload it to server etc.
        byte[] bytes = screenshot.EncodeToPNG();
    }
}
추천 기사
유니티 FPS 카운터
Unity용 2D 근접 공격 튜토리얼
Unity용 카운트다운 타이머 튜토리얼
Zone Controller Pro - Unity 에셋 스토어 패키지
Unity에서 새로운 HDRP 급수 시스템을 사용하는 방법
FPC Swimmer - 몰입형 수중 환경을 위한 포괄적인 Unity 에셋
Ultimate Spawner 2.0 - 판도를 바꾸는 자산