在 Canvas 上显示 DrawingVisual
Display a DrawingVisual on Canvas
我有绘图视觉效果,我有绘图,如何将其添加到我的 canvas 并显示?
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 作为
Canvas canvas = null;
canvas.Children.Add(drawingVisual); //Doesnt work as UIElement expected.
如何将我的 drawingVisual 添加到 canvas?
TIA。
您必须实现一个宿主元素 class,它必须重写派生的 UIElement 或 FrameworkElement 的 VisualChildrenCount
属性 和 GetVisualChild()
方法 return 你的 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 添加视觉效果:
canvas.Children.Add(new VisualHost { Visual = drawingVisual });
我有绘图视觉效果,我有绘图,如何将其添加到我的 canvas 并显示?
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 作为
Canvas canvas = null;
canvas.Children.Add(drawingVisual); //Doesnt work as UIElement expected.
如何将我的 drawingVisual 添加到 canvas?
TIA。
您必须实现一个宿主元素 class,它必须重写派生的 UIElement 或 FrameworkElement 的 VisualChildrenCount
属性 和 GetVisualChild()
方法 return 你的 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 添加视觉效果:
canvas.Children.Add(new VisualHost { Visual = drawingVisual });