Skip to content

Instantly share code, notes, and snippets.

@allfake
Last active August 9, 2022 09:37
Show Gist options
  • Save allfake/54003099175c03a85a11c4ea1cc2e22b to your computer and use it in GitHub Desktop.
Save allfake/54003099175c03a85a11c4ea1cc2e22b to your computer and use it in GitHub Desktop.
Unity Canvas - Use screen space Camera
using System.Collections;
using System.IO;
using UnityEngine;
namespace Utils
{
public static class CaptureRect
{
public static IEnumerator Capture(RectTransform rectT, string savePath)
{
// your capture canvas
var mainCanvasRect = GameObject.FindWithTag(TagHelper.MainUICanvas).GetComponent<RectTransform>();
var camera = Camera.main.GetComponent<Camera>();
yield return new WaitForEndOfFrame();
var screenPos = camera.WorldToScreenPoint(rectT.gameObject.transform.position);
var resHeight = (int)((rectT.sizeDelta.y / mainCanvasRect.sizeDelta.y) * Screen.height);
var resWidth = (int)((rectT.sizeDelta.x / mainCanvasRect.sizeDelta.x) * Screen.width);
var heightOffset = (int) (-resHeight * 0.5f + screenPos.y);
var widthOffset = (int) (-resWidth * 0.5f + screenPos.x);
RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 24);
camera.targetTexture = rt;
Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
camera.Render();
RenderTexture.active = rt;
screenShot.ReadPixels(new Rect(widthOffset, heightOffset, resWidth, resHeight), 0, 0);
camera.targetTexture = null;
RenderTexture.active = null;
GameObject.Destroy(rt);
var bytes = screenShot.EncodeToPNG();
File.WriteAllBytes(savePath, bytes);
GameObject.Destroy(screenShot);
}
}
}
@allfake
Copy link
Author

allfake commented May 27, 2022

// example
StartCoroutine(CaptureRect.Capture(gameObject.GetComponent<RectTransform>(), Application.dataPath + "ScreenShot.png"));

@allfake
Copy link
Author

allfake commented Jul 1, 2022

Set rectT Anchors to min 0,1 max 0,1 (Top-Left)

@allfake
Copy link
Author

allfake commented Jul 1, 2022

Change Anchors From min [0,0] max [1,1] to min [0,1] max [0,1] (Top-Left)

var size = captureRect.rect.size;
var pos = Vector2.zero;
pos.x = Mathf.FloorToInt(size.x / 2);
pos.y = -Mathf.FloorToInt(size.y / 2);
captureRect.anchorMin = Vector2.up;
captureRect.anchorMax = Vector2.up;
captureRect.anchoredPosition = pos;
captureRect.sizeDelta = size;

@allfake
Copy link
Author

allfake commented Aug 9, 2022

Error will show if content cannot display in screen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment