1

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

目前,我通过使用原始 Canvas 的 VisualBrush 将 Canvas 转换为 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);
}

然后我剪辑生成的 Rectangle 以将其裁剪为大小:

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 来分析生成的剪辑 Canvas 并检测是否存在任何内容,但不知道该怎么做。在表示目标页面大小的原始画布上绘制一个矩形也是合理的,并检查是否有任何其他元素出现在其边界/碰撞内。我不确定。获得返回值或 null 之类的就可以了,我只需要通过整个路径找出我的裁剪部分没有内容。

4

1 回答 1

0

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

于 2015-12-29T21:19:36.713 回答