来自VisualTreeHelper.GetDescendantBounds()的MSDN文档:
// Return the bounding rectangle of the parent visual object and all of its descendants.
Rect rectBounds = VisualTreeHelper.GetDescendantBounds(parentVisual);
我得到了这个并且它有效,但我不想要包含父级的边界,原因是我的父级是XPS文档的页面,所以调用它只是返回页面边界,这不是我想要的。我想要页面上所有内容的边界框,即页面视觉的子项。
// snippet of my code
Visual visual = paginator.GetPage(0).Visual;
Rect contentBounds = VisualTreeHelper.GetDescendantBounds(visual);
// above call returns the page boundaries
// is there a way to get the bounding box of just the children of the page?
我需要这个的原因是我将XPS页面保存到位图并且需要包含尽可能少的空白区域,以将位图限制为仅页面的“已使用”区域。
我是否需要自己迭代视觉的所有孩子并在每个孩子上调用VisualTreeHelper.GetContentBounds()?我认为会有比这更好的方式......
答案 0 :(得分:2)
通过枚举父(页面)视觉的所有子视觉效果,我想出了一个可行的解决方案。更高效和/或库解决方案会更好,但现在可以使用。
// enumerate all the child visuals
List<Visual> children = new List<Visual>();
EnumVisual(visual, children);
// loop over each child and call GetContentBounds() on each one
Rect? contentBounds = null;
foreach (Visual child in children)
{
Rect childBounds = VisualTreeHelper.GetContentBounds(child);
if (childBounds != Rect.Empty)
{
if (contentBounds.HasValue)
{
contentBounds.Value.Union(childBounds);
}
else
{
contentBounds = childBounds;
}
}
}
/// <summary>
/// Enumerate all the descendants (children) of a visual object.
/// </summary>
/// <param name="parent">Starting visual (parent).</param>
/// <param name="collection">Collection, into which is placed all of the descendant visuals.</param>
public static void EnumVisual(Visual parent, List<Visual> collection)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
// Get the child visual at specified index value.
Visual childVisual = (Visual)VisualTreeHelper.GetChild(parent, i);
// Add the child visual object to the collection.
collection.Add(childVisual);
// Recursively enumerate children of the child visual object.
EnumVisual(childVisual, collection);
}
}