wpf 在画布上显示 DrawingVisual
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36126505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display a DrawingVisual on Canvas
提问by Joga
I have a drawing visual which I have drawings, how do I add this to my canvas and display?
我有一个绘图视觉对象,我有绘图,如何将它添加到我的画布并显示?
DrawingVisual drawingVisual = new DrawingVisual();
// Retrieve the DrawingContext in order to create new drawing content.
DrawingContext drawingContext = drawingVisual.RenderOpen();
// Create a rectangle and draw it in the DrawingContext.
Rect rect = new Rect(new System.Windows.Point(0, 0), new System.Windows.Size(100, 100));
drawingContext.DrawRectangle(System.Windows.Media.Brushes.Aqua, (System.Windows.Media.Pen)null, rect);
// Persist the drawing content.
drawingContext.Close();
How do I add this to a canvas? Suppose I have a Canvas as
如何将其添加到画布?假设我有一个 Canvas 作为
Canvas canvas = null;
canvas.Children.Add(drawingVisual); //Doesnt work as UIElement expected.
How do I add my drawingVisual to canvas?
如何将我的绘图视觉添加到画布?
TIA.
TIA。
回答by Clemens
You have to implement a host element class, which would have to override the VisualChildrenCountproperty and the GetVisualChild()method of a derived UIElement or FrameworkElement to return your DrawingVisual.
您必须实现一个宿主元素类,该类必须覆盖派生的 UIElement 或 FrameworkElement的VisualChildrenCount属性和GetVisualChild()方法才能返回您的 DrawingVisual。
The most basic implementation could look like this:
最基本的实现可能如下所示:
public class VisualHost : UIElement
{
public Visual Visual { get; set; }
protected override int VisualChildrenCount
{
get { return Visual != null ? 1 : 0; }
}
protected override Visual GetVisualChild(int index)
{
return Visual;
}
}
Now you would add a Visual to your Canvas like this:
现在你可以像这样向你的画布添加一个视觉效果:
canvas.Children.Add(new VisualHost { Visual = drawingVisual });

