Take a screenshot using a rect transform without it being affected by the screen size in Unity using C#


One possible way to take a screenshot using a rect transform without it being affected by the screen size in Unity using C#  is to use the Camera.WorldToScreenPoint method to convert the four corners of the rect transform to screen pointsThen, you can use Texture.ReadPixels with a Rect as calculated from the screen points to save it into a textureYou may need to adjust the y-axis depending on your camera settings.

Here are some possible steps and c# code example for taking a screenshot using a rect transform:

  • Assign the rect transform object that you want to screenshot to a variable (e.g. _objToScreenshot) .
  • Convert the four corners of the rect transform to world points using _objToScreenshot.GetWorldCorners method 1.
  • Convert the world points to screen points using Camera.WorldToScreenPoint method .
  • Adjust the y-axis if needed by subtracting it from Screen.height .
  • Calculate the width and height of the rect transform in screen space by subtracting the minimum x and y values from the maximum x and y values .
  • Create a new texture with the width and height of the rect transform 1.
  • Use Texture.ReadPixels with a Rect as calculated from the screen points to save it into the texture .
  • Encode the texture as PNG and save it to disk using System.IO.File.WriteAllBytes method 1.

An example code for this method is:

csharp
using System.Collections; using UnityEngine; using UnityEngine.UI; public class TakeScreenshotAndSave : MonoBehaviour { //Object To Screenshot [SerializeField] private RectTransform _objToScreenshot; //Set the button to take a screenshot when pressed public Button btnTakeScreenshot; private void Start() { btnTakeScreenshot.onClick.AddListener(TakeScreenShot); } private void TakeScreenShot() { //Get four corners of object in world space Vector3[] v = new Vector3[4]; _objToScreenshot.GetWorldCorners(v); //Convert world space corners to screen space Vector2[] v2 = new Vector2[4]; for (int i = 0; i < 4; i++) { v2[i] = Camera.main.WorldToScreenPoint(v[i]); //Adjust y-axis if needed v2[i].y = Screen.height - v2[i].y; } //Calculate width and height of object in screen space float width = Mathf.Abs(v2[0].x - v2[1].x); float height = Mathf.Abs(v2[0].y - v2[1].y); //Using that size, create a new texture. Texture2D tex = new Texture2D((int)width, (int)height); //Read pixels from screen into texture tex.ReadPixels(new Rect(v2[0], new Vector2(width, height)), 0, 0); //Encode texture as PNG and save it to disk byte[] bytes = tex.EncodeToPNG(); //You can change this path according to your needs string path = Application.dataPath + "/screenshot.png"; System.IO.File.WriteAllBytes(path, bytes); Debug.Log("Saved screenshot at " + path); } }