gpt4 book ai didi

c# - 在 Canvas 上显示 DrawingVisual

转载 作者:行者123 更新时间:2023-11-30 19:24:29 28 4
gpt4 key购买 nike

我有一个绘图视觉对象,我有绘图,如何将它添加到我的 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。

最佳答案

您必须实现一个宿主元素类,它必须重写派生的 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 添加视觉效果:

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

关于c# - 在 Canvas 上显示 DrawingVisual,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36126505/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com