Last active
August 9, 2022 09:37
-
-
Save allfake/54003099175c03a85a11c4ea1cc2e22b to your computer and use it in GitHub Desktop.
Unity Canvas - Use screen space Camera
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Error will show if content cannot display in screen.