Getting the true visual bounding box of a WPF element?

前端 未结 3 1076
醉话见心
醉话见心 2020-12-18 05:53

For a simplified version of my problem, I would like to calculate the bounding box of a layout-transformed (possibly even render-transformed) shape, so that I can always fit

相关标签:
3条回答
  • 2020-12-18 05:58
    private Rect GetRectOfObject(FrameworkElement _element)
    {
        Rect rectangleBounds = new Rect();
        rectangleBounds = _element.RenderTransform.TransformBounds(new Rect(0, 0, _element.Width, _element.Height));
        return rectangleBounds;
    }
    

    Maybe this will help out.

    0 讨论(0)
  • 2020-12-18 06:17

    The problem is not easy, as a control may draw outside its bounds.

    But if you assume this doesn't happen you can solve the problem by using parent.TranslatePoint(point_in_child_coord_system, child) to transform (0,0), (child.ActualWidth,0), (child.ActualWidth, child.ActualHeight) and (0,child.ActualHeight) to the parent coord system. Then sort the x and y coordinates of all points and use minimum and maximum values to find the bounding box.

    Note: sorting is necessary because of possible child rotation.

    0 讨论(0)
  • 2020-12-18 06:20

    You will get good results with VisualTreeHelper.GetDescendantBounds() and you can use VisualTreeHelper.GetParent() to gain access to the otherwise protected VisualParent property. However what you probably want to do is call GetDescendantBounds on the shape itself, not its parent, because in spite of its name, the method returns the bounds of the parent and all of its decendants.

    0 讨论(0)
提交回复
热议问题