본문 바로가기
개발/Unity

Unity) 화면 캡쳐(Screen Capture)

by 테샤르 2022. 7. 28.

화면 캡쳐(Screen Capture)

화면을 캡처하는데 사용하는 코드이다.

화면을 가져오는 여러가지 방법이 있는데 Camera.targetTexture와

RenderTexture.active를 통해서 화면을 가져오는 코드이다.

 

   public static bool TakeScreenshot(string path, ImageFormat format, Camera cam = null)
   {
       if (cam != null || format != ImageFormat.Png)
       {
           Texture2D screenshot;
           if (cam != null)
           {
               var tmp = RenderTexture.GetTemporary(cam.pixelWidth, cam.pixelHeight);
               var cache = cam.targetTexture;
               cam.targetTexture = tmp;
               cam.Render();

               RenderTexture.active = tmp;
               screenshot = new Texture2D(tmp.width, tmp.height, TextureFormat.ARGB32, false);
               screenshot.ReadPixels(new Rect(0, 0, tmp.width, tmp.height), 0, 0);

               RenderTexture.active = null;

               cam.targetTexture = cache;
               tmp.Release();
           }
           else
           {
               screenshot = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
               screenshot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
               screenshot.Apply();
           }

           byte[] bytes;
           bytes = format.ToString() switch
           {
                "Png"=> screenshot.EncodeToPNG(),
               "Jpeg" => screenshot.EncodeToJPG(),
           };
         
           System.IO.File.WriteAllBytes(path, bytes);

           UnityEngine.Object.DestroyImmediate(screenshot);
           return true;
       }
       else
       {
           ScreenCapture.CaptureScreenshot(path);
           return true;
       }
   }

 

 

반응형

정적인 순간에서는 계속적인 렌더링하는것보다는 카메라 텍스처로 렌더링하는게 유용하다.

 

 

참고 사이트 : [링크]

 

[unity development tips] four patterns of unity screenshots - Develop Paper

Welcome to unity QQ exchange group: 956187480 Method 1: full screen screenshot of the built-in API ScreenCapture Screensapture is a full screen screenshot, which can directly read pixels. There are scenes and UIThere are two screenshots in this way, and th

developpaper.com

 

Unity ScreenCapture.CaptureScreenShot : [링크]

 

Unity RenderTexture.active  : [링크]

 

RenderTexture-active - Unity 스크립팅 API

Currently active render texture.

docs.unity3d.com

Unity Camera.targetTexture : [링크]

 

Unity - Scripting API: Camera.targetTexture

Usually cameras render directly to screen, but for some effects it is useful to make a camera render into a texture. This is done by creating a RenderTexture object and setting it as targetTexture on the camera. The camera will then render into that textur

docs.unity3d.com

 

★☆☆☆☆

 

반응형

댓글