LoginSignup
1

More than 3 years have passed since last update.

[Unity] 指定した範囲を切り抜いたスクショを保存する

Last updated at Posted at 2019-09-07

目的

スクショを撮ったときに指定した範囲だけ切り出してから保存したい。

例えば次の画面があるとときに、
ss_1136_640.png

画面全体では1136 * 640だが、画面中央付近の500*500の画像を撮りたい場合がある。

方法

Texture2Dの機能を使うとできた。

        protected virtual IEnumerator CaptureCoroutine(int width, int height)
        {
            // カメラのレンダリング待ち
            yield return new WaitForEndOfFrame();
            Texture2D tex = ScreenCapture.CaptureScreenshotAsTexture();
            // 切り取る画像の左下位置を求める
            int x = (tex.width - width) / 2;
            int y = (tex.height - height) / 2;
            Color[] colors = tex.GetPixels(x, y, width, height);
            Texture2D saveTex = new Texture2D(width, height, TextureFormat.ARGB32, false);
            saveTex.SetPixels(colors);
            File.WriteAllBytes("ss.png", saveTex.EncodeToPNG());
        }

上のCoroutineに500,500を引数に渡して呼び出すと、Unity Projectのrootディレクトリ直下に"ss.png"という名前で次の画像が作られる。

ss.png

やっていること

  • ScreenCapture.CaptureScreenshotAsTextureでスクショをTexture2Dで扱う
  • Texture2DのGetPixelsメソッドを使い指定した範囲を切り抜いた部分をColorの配列にする
  • 保存用Texture2Dに作ったColorの配列を入れ、EncodeToPNGメソッドを使ってPNGとして保存させる。

Coroutine化してWaitForEndOfFrameまで待つのは、今回使ったScreenCapture.CaptureScreenshotAsTextureで得られる画像がおかしくなるため。ドキュメントにも注意が書かれている。多分カメラのレンダリング以降に呼び出さないとだめなのかな。

試しにWaitForEndOfFrameせずに撮影した場合は次の画像になり期待したものにはならなかった。
ss_bug.png

スクショを保存する機能のScreenCapture.CaptureScreenshotはいつ呼び出しても使えそうだが、CaptureScreenshotAsTextureはそうではないので気をつけたい。

まとめ

  • ScreenCapture.CaptureScreenshotAsTextureとTexture2Dの機能を使えば画面の指定した範囲を切り抜いたスクショをつくることができる。
  • ScreenCapture.CaptureScreenshotAsTextureは呼び出すタイミングに気をつける。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1