在画布上显示DrawingVisual

时间:2016-03-21 08:52:41

标签: c# wpf canvas drawing drawingcontext

我有一个绘图视觉,我有绘图,如何将其添加到我的画布和显示?

 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();

如何将其添加到画布?假设我有一个画布

  Canvas canvas = null;
  canvas.Children.Add(drawingVisual); //Doesnt work as UIElement expected.

如何将drawingVisual添加到画布?

TIA。

1 个答案:

答案 0 :(得分:7)

您必须实现一个host元素类,它必须覆盖派生的UIElement或FrameworkElement的VisualChildrenCount属性和GetVisualChild()方法才能返回您的DrawingVisual。

最基本的实现可能如下所示:

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;
    }
}

现在,您可以像这样在Canvas中添加一个Visual:

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