c# - 如何获取 WPF 视觉对象的子边界框,不包括父对象

标签 c# wpf graphics xps

来自 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()在每个?我认为会有比这样做更好的方法......

最佳答案

我通过枚举父(页面)视觉对象的所有子视觉对象提出了一个可行的解决方案。更高效和/或库的解决方案会更好,但这目前有效。

// 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);
    }
}           

关于c# - 如何获取 WPF 视觉对象的子边界框,不包括父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7314287/

相关文章:

c# - 复杂的 C# Linq 算法

c# - 如何让 XAML 中的图像显示为它们的实际大小?

c# - 数组类型声明 C#

wpf - 附加属性的样式触发器

wpf - 按钮模板没有清晰地呈现图像

java - 在Java中,如何防止图形Applet多次运行?

c# - SSRS 展开 Tablix 以填充页面

c# - 将 Winform 应用程序转换为 WPF 应用程序

java - 图形对象被抑制

javascript - X Windows 风格的 JS UI 客户端