【问题标题】:Display a DrawingVisual on Canvas在画布上显示 DrawingVisual
【发布时间】:2016-07-07 16:39:43
【问题描述】:

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

 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 = null;
  canvas.Children.Add(drawingVisual); //Doesnt work as UIElement expected.

如何将 drawingVisual 添加到画布?

TIA。

【问题讨论】:

    标签: c# wpf canvas drawing drawingcontext


    【解决方案1】:

    您必须实现一个宿主元素类,该类必须覆盖派生 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.Children.Add(new VisualHost { Visual = drawingVisual });
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2016-02-25
      • 2015-01-22
      • 2011-07-19
      • 2012-10-17
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      相关资源
      最近更新 更多