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也是合理的,並檢查其邊界/碰撞中是否出現其他元素。我不確定。 這將是很好,得到一個返回值或空或什麼的,我只需要通過這整個路徑的一些手段來找出我的裁剪部分沒有內容存在。