public static Rect GetScreenRectFromRectTransform(RectTransform rectTransform)
{
Vector3[] corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
float xMin = float.PositiveInfinity;
float xMax = float.NegativeInfinity;
float yMin = float.PositiveInfinity;
float yMax = float.NegativeInfinity;
for (int i = 0; i < 4; i++)
{
// For Canvas mode Screen Space - Overlay there is no Camera; best solution I've found
// is to use RectTransformUtility.WorldToScreenPoint) with a null camera.
Vector3 screenCoord = RectTransformUtility.WorldToScreenPoint(null, corners[i]);
if (screenCoord.x < xMin)
xMin = screenCoord.x;
if (screenCoord.x > xMax)
xMax = screenCoord.x;
if (screenCoord.y < yMin)
yMin = screenCoord.y;
if (screenCoord.y > yMax)
yMax = screenCoord.y;
}
Rect result = new Rect(xMin, Screen.height - yMax, xMax - xMin, yMax - yMin);
return result;
}