Add Rect.Expand(Vector2)

Issue #131 resolved
Johannes P. created an issue

It would be useful to have an Expand extension method in Sirenix.Utilities.RectExtensions to include a given Vector2.

Example Implementation

// Returns a Rect expanded to contain the given position
public static Rect Expand(this Rect rect, Vector2 pos)
    Rect result = new Rect(rect);

    if (pos.x < result.xMin) 
        result.xMin = pos.x;
    else if (pos.x > result.xMax) 
        result.xMax = pos.x;

    if (pos.y < result.yMin) 
         result.yMin = pos.y;
    else if (pos.y > result.yMax) 
         result.yMax = pos.y;

    return result;


static void RunDemo()
    Rect test = new Rect(new Vector2(1, 2), new Vector2(2, 3));
    PrintRectBounds(test); // x[1:3], y[2:5]

    // Expand only x
    test = test.Expand(new Vector2(7, 4));
    PrintRectBounds(test); // x[1:7], y[2:5]

    // Expand only y
    test = test.Expand(new Vector2(4, 8));
    PrintRectBounds(test); // x[1:7], y[2:8]


    // Expand both x and y
    test = test.Expand(new Vector2(-2, -3));
    PrintRectBounds(test); // x[-2:7], y[-3:8] 

static void PrintRectBounds(Rect rect)
    Debug.LogFormat("x[{0}:{1}], y[{2}:{3}]", 
        rect.xMin, rect.xMax, rect.yMin, rect.yMax);

Comments (7)

  1. Tor Esa Vestergaard

    A fine idea. We've redubbed this ExpandTo, and included essentially this in the RectExtensions class. It'll be in the next patch.

  2. Log in to comment