简体   繁体   English

在画布上显示DrawingVisual

[英]Display a DrawingVisual on Canvas

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? 如何将drawingVisual添加到画布?

TIA. TIA。

You have to implement a host element class, which would have to override the VisualChildrenCount property and the GetVisualChild() method of a derived UIElement or FrameworkElement to return your DrawingVisual. 您必须实现一个host元素类,它必须覆盖VisualChildrenCount属性和派生的UIElement或FrameworkElement的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添加一个Visual,如下所示:

canvas.Children.Add(new VisualHost { Visual = drawingVisual });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM