2015-12-09 78 views
1

我有一个大的画布,我试图分页打印。我可以将画布分成页面大小的部分,可以裁剪(剪辑)内容,并将每个页面传递给打印方法。我想跳过空白页面,但需要一些手段来检测内容是空白的。如何检测裁剪/裁剪WPF FrameworkElement/Canvas是否有任何内容?

目前,我通过将其与原始画布的VisualBrush转换为矩形“变平”一画布:

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也是合理的,并检查其边界/碰撞中是否出现其他元素。我不确定。 这将是很好,得到一个返回值或空或什么的,我只需要通过这整个路径的一些手段来找出我的裁剪部分没有内容存在。

回答

0

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