2014년 5월 1일 목요일

Unity_Screen Capture.cs _ Screen Shot


Explanation.
현재 게임 화면 캡쳐기능.
현재 스크린 그대로를 readpixel하는 방식이라
OnGUI로 그려지는 UI는 캡쳐X
스크린 사이즈 그대로 RGB24 포멧으로 저장.

ScreenCapture.cs
using UnityEngine;
using System.Collections;
using System.IO;

public class ScreenCapture : MonoBehaviour
{
    int height = Screen.height;
    int width = Screen.width;

    Texture2D captureTexture;
    float startTime;
    string saveDir = "ScreenShot"; // 저장 폴더 이름.

    bool draw = false;
    void OnGUI()
    {
        if (GUI.Button(new Rect(10, 50, 100, 50), "Capture"))
        {
            StartCoroutine(screenCapture());
        }
    }

    IEnumerator screenCapture()
    {
        yield return new WaitForEndOfFrame();
        captureTexture = new Texture2D(width, height, TextureFormat.RGB24, true); // texture formoat setting
        captureTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0, true); // readPixel
        captureTexture.Apply(); // readPixel data apply

        byte[] bytes = captureTexture.EncodeToPNG();

        File.WriteAllBytes(getCaptureName(), bytes);
        Debug.Log(string.Format("Capture Success: {0}", getCaptureName()));

    }
    string getCaptureName()
    {
        string dirPath = Application.dataPath + "/" + saveDir;
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }
        return string.Format("{0}/capture_{1}.png",
                             dirPath,
                             System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
    }
    
}
Categories:

댓글 2개:

  1. 스마트폰에 저장을 하려면 어떻게 해야 할까요 ㅠ
    안드로이드 갤럭시 노트 5입니다 되질 않아서 ㅠ

    답글삭제
  2. Application.dataPath -> Application.persistentDataPath 으로 변경하시면 됩니다.

    답글삭제