0

Is there a simple way to find the rectangle (area and location) that would be required to cover a set of control?? VisualTreeHelper.GetDescandentBounds() works fine, but there are no overloaded methods where I can specify the controls that it should consider for finding the bounds rectangle. Any simple solution will be greatly appreciated.

Thanks

sudarsanyes
  • 3,156
  • 8
  • 42
  • 52

1 Answers1

2

Rect has a Union(Rect) method, which enlarges the current rect to also include the second rectangle. With linq (dont forget to add using System.Linq; to your code file) it's also fairly simple to get a list of rectangles for a list of visuals:

private Rect GetBoundingRect(Visual relativeTo, List<Visual> visuals)
{
    Vector relativeOffset  = new Point() - relativeTo.PointToScreen(new Point());

    List<Rect> rects = visuals
        .Select(v => new Rect(v.PointToScreen(new Point()) + relativeOffset, VisualTreeHelper.GetDescendantBounds(v).Size))
        .ToList();

    Rect result = rects[0];
    for (int i = 1; i < rects.Count; i++)
        result.Union(rects[i]);
    return result;
}       

Edited code: It will now take the position of the individual visuals into account relative to the given visual.

Bubblewrap
  • 7,266
  • 1
  • 35
  • 33
  • It doesn't give the unified rectangle because the Visuals might appear at difference corners of the parent panel and the calculation in this snippet is based on the visual's descendant bound and not with respect to the parent panel. – sudarsanyes Sep 08 '10 at 09:29
  • So, if I have 5 buttons (with same size) arranged in different corners of a panel, the method is always returning a rectangle that resembles a single button's size. actually i need it to return a rectangle that can accommodate all the five buttons. any idea on how to achieve this ?? – sudarsanyes Sep 08 '10 at 09:32