티스토리 뷰

스크린샷을 찍는 방법은 정말 쉽다. 한 줄이면 된다.

ScreenCapture.CaptureScreenshot(string 파일명, int 사이즈)

이 한줄만 쓰면 자동으로 Application.persistentDataPath 경로에 PNG 파일로 저장된다.

하지만 모바일 갤러리에는 갱신이 되지 않는다.


그럴 땐


깃허브에서 UnityNativeGallery를 받아서 광명을 찾자!!

ios도 안드로이드도 모두 작동된다고 쓰여있다.

일단 안드로이드 테스트는 마친상태이다.


깃허브 자체 설명만 보고 따라해도 충분하며, 좀 더 알아보고 싶다면

https://blog.csdn.net/weixin_39706943/article/details/81196089 이 링크와

https://forum.unity.com/threads/save-png-to-gallery.464013/ 이 링크를 참조해도 좋다.


01. 일단 초록버튼을 눌러 ZIP파일을 다운로드 받자.





02. 압축을 풀고 유니티 패키지를 유니티 에디터 상에 푼다.


03. 예제 코드


Screenshot.cs 생성

스크린샷을 찍고, 갱신한다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;
 
public class Screenshot : MonoBehaviour
{
    public GameObject blink;             // 사진 찍을 때 깜빡일 것
    public GameObject shareButtons;      // 공유 버튼
 
    bool isCoroutinePlaying;             // 코루틴 중복방지
 
    // 파일 불러올 때 필요
    string albumName = "Test";    // 생성될 앨범의 이름
    [SerializeField]
    GameObject panel;                    // 찍은 사진이 뜰 패널
 
 
    // 캡쳐 버튼을 누르면 호출
    public void Capture_Button()
    {
        // 중복방지 bool
        if (!isCoroutinePlaying)
        {
            StartCoroutine("captureScreenshot");
        }
    }
 
    IEnumerator captureScreenshot()
    {
        isCoroutinePlaying = true;
 
        // UI 없앤다...
 
        yield return new WaitForEndOfFrame();
 
        // 스크린샷 + 갤러리갱신
        ScreenshotAndGallery();
 
        yield return new WaitForEndOfFrame();
 
        // 블링크
        BlinkUI();
 
        // 셔터 사운드 넣기...
 
        yield return new WaitForEndOfFrame();
 
        // UI 다시 나온다...
 
        yield return new WaitForSecondsRealtime(0.3f);
 
        // 찍은 사진이 등장
        GetPirctureAndShowIt();
 
        isCoroutinePlaying = false;
    }
 
    // 흰색 블링크 생성
    void BlinkUI()
    {
        GameObject b = Instantiate(blink);
        b.transform.SetParent(transform);
        b.transform.localPosition = new Vector3(000);
        b.transform.localScale = new Vector3(111);
    }
 
    // 스크린샷 찍고 갤러리에 갱신
    void ScreenshotAndGallery()
    {
        // 스크린샷
        Texture2D ss = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        ss.ReadPixels(new Rect(00, Screen.width, Screen.height), 00);
        ss.Apply();
 
        // 갤러리갱신
        Debug.Log("" + NativeGallery.SaveImageToGallery(ss, albumName,
            "Screenshot_" + System.DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss"+ "{0}.png"));
 
        // To avoid memory leaks.
        // 복사 완료됐기 때문에 원본 메모리 삭제
        Destroy(ss);
 
    }
    // 찍은 사진을 Panel에 보여준다.
    void GetPirctureAndShowIt()
    {
        string pathToFile = GetPicture.GetLastPicturePath();
        if (pathToFile == null)
        {
            return;
        }
        Texture2D texture = GetScreenshotImage(pathToFile);
        Sprite sp = Sprite.Create(texture, new Rect(00, texture.width, texture.height), new Vector2(0.5f, 0.5f));
        panel.SetActive(true);
        shareButtons.SetActive(true);
        panel.GetComponent<Image>().sprite = sp;
    }
    // 찍은 사진을 불러온다.
    Texture2D GetScreenshotImage(string filePath)
    {
        Texture2D texture = null;
        byte[] fileBytes;
        if (File.Exists(filePath))
        {
            fileBytes = File.ReadAllBytes(filePath);
            texture = new Texture2D(22, TextureFormat.RGB24, false);
            texture.LoadImage(fileBytes);
        }
        return texture;
    }
}
 

cs



GetPicture.cs 생성

사진이 저장된 경로를 가져온다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
 
public class GetPicture : MonoBehaviour {
 
// 사진이 저장된 경로를 가져올 때 필요
#if !UNITY_EDITOR && UNITY_ANDROID
    private static AndroidJavaClass m_ajc = null;
    private static AndroidJavaClass AJC
    {
        get
        {
            if (m_ajc == null)
                m_ajc = new AndroidJavaClass("com.yasirkula.unity.NativeGallery");
 
            return m_ajc;
        }
    }
#endif
    
// 다른 스크립트에서 GetPicture.GetLastPicturePath()로 호출
    public static string GetLastPicturePath()
    {
        // 디바이스마다 다른 저장경로
        string saveDir;
        #if !UNITY_EDITOR && UNITY_ANDROID
        saveDir = AJC.CallStatic<string>"GetMediaPath""Shine Bright" );
        #else
        saveDir = Application.persistentDataPath;
        #endif
        // 저장경로에서 PNG파일 모두 검색
        string[] files = Directory.GetFiles(saveDir, "*.png");
        // 만약 PNG파일이 있다면, 마지막 파일을 반환
        if (files.Length > 0)
        {
            return files[files.Length - 1];
        }
        // 없다면 null을 
        return null;
    }
 
 
}
 
cs



공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
글 보관함