如何检测裁剪/裁剪的WPF FrameworkElement / Canvas是否有任何内容?

时间:2015-12-09 16:56:00

标签: wpf canvas clip frameworkelement

我有一个大型Canvas,我正试图打印以进行打印。我可以将画布分成页面大小的部分,有一种方法可以裁剪(剪辑)内容,并将每个页面传递给打印方法。我想跳过空白页面,并且需要一些方法来检测内容是否为空白。

目前,我通过将Canvas转换为带有原始Canvas的VisualBrush的Rectangle来“展平”Canvas:

public Rectangle createRectanglefromUI(UIElement ui)
{
    VisualBrush myVisualBrush = new VisualBrush();
    myVisualBrush.Visual = ui;

    Rectangle myRectangle = new Rectangle();
    double w = ((FrameworkElement)ui).ActualWidth;
    double h = ((FrameworkElement)ui).ActualHeight;
    double ratio = w / h;

    myRectangle.Width = 150;
    myRectangle.Height = 150 / ratio;
    myRectangle.StrokeThickness = 0;
    myVisualBrush.Stretch = Stretch.Uniform;
    myRectangle.Margin = new Thickness(0, 0, 0, 0);
    myRectangle.Fill = myVisualBrush;

    return (myRectangle);
}

然后剪切生成的矩形以将其裁剪为大小:

private Canvas cropUIElement(double desiredWidth, double desiredHeight, int leftCoordinate, int topCoordinate, FrameworkElement uiELement, int scaleFactor = 1)
{
    try
    {
        // Create a clip for masking undesired content from the element
        Rect clipRectangle = new Rect(leftCoordinate * desiredWidth, topCoordinate * desiredHeight, desiredWidth, desiredHeight);
        RectangleGeometry clipGeometry = new RectangleGeometry(clipRectangle);

        ScaleTransform clipScale = new ScaleTransform(scaleFactor, scaleFactor, 0, 0);

        Rectangle flattenedUIElement = createRectanglefromUI(uiELement);

        flattenedUIElement.Clip = clipGeometry;
        flattenedUIElement.LayoutTransform = clipScale;
        flattenedUIElement.ClipToBounds = true;

        Canvas outputElement = new Canvas();

        Canvas.SetLeft(
            flattenedUIElement, -1 * scaleFactor * (leftCoordinate * desiredWidth));
        Canvas.SetTop(
             flattenedUIElement, -1 * scaleFactor * (topCoordinate * desiredHeight));

        // Configuring width and height determines the final element size.
        outputElement.Width = scaleFactor * desiredWidth;
        outputElement.Height = scaleFactor * desiredHeight;

        outputElement.Children.Add(flattenedUIElement);
            // Default behavior is ClipToBounds = false. True creates the cropping effect.
        outputElement.ClipToBounds = true;

        return outputElement;
    }
    catch (SystemException)
    {
        return null;
    }
}

我想也许我可以使用XamlWriter来分析生成的剪切画布,并检测是否存在任何内容,但不知道如何去做。在原始画布上绘制一个表示目标页面大小的Rectangle也是合理的,并检查是否在其bounds / collide中出现任何其他元素。我不确定。 获得返回值或null或其他东西会很好,我只需要通过整个路径找出我的裁剪部分没有内容。

1 个答案:

答案 0 :(得分:0)

它效率低下,但我最终做的是将剪裁区域(由cropUIElement产生)与Canvas的所有子项进行比较,检查bout .IntersectsWith(child)和.Contains(child)。我最终遍历所有项目,但它确实有效。