I'm attempting to get the pixel-perfect bounding box for multiple UI elements in my scene, ensuring there are no empty spaces around the sprites. Is it possible to achieve this without checking for each individual pixel?
private void OnDrawGizmos()
{
var min = Vector3.positiveInfinity;
var max = Vector3.negativeInfinity;
foreach (var image in imageList)
{
if(!image) continue;
// Get the 4 corners in world coordinates
var v = new Vector3[4];
image.rectTransform.GetWorldCorners(v);
// update min and max
foreach (var vector3 in v)
{
min = Vector3.Min(min, vector3);
max = Vector3.Max(max, vector3);
}
}
// create the bounds
var bounds = new Bounds();
bounds.SetMinMax(min, max);
Gizmos.color = Color.red;
Gizmos.DrawWireCube(bounds.center, bounds.extents*2);
}
This code produces the red box in this image below. But, what I'm after is the yellow box.
(Sprites are generated by user)



Maybe you can add PolygonCollider2D on them, and configure editor time. Then at the runtime, you can create new Bounds, and get bounds of all colliders Collider2D.Bounds, and use Bounds.Encapsulate.
P.S. I am not sure if will it work for a UI Element...