0

所以,我是 WPF 绘图的新手。出于性能原因,我不得不从 ContentControl 和 UserControl 等常规控件切换到更轻量级的元素,例如 DrawingVisual。我正在开发一个图表应用程序,它可能在画布上最多有 1000 个元素,可以拖动、调整大小等。首先,使用 DrawingVisual 代替 Shape 更好吗?其次,我的主要问题在这里。我正在向 Canvas 添加 DrawingVisual 元素,如下所示:

public class SVisualContainer : UIElement
{
    // Create a collection of child visual objects.
    private VisualCollection _children;

    public SVisualContainer()
    {
        _children = new VisualCollection(this);
        _children.Add(CreateDrawingVisualRectangle());
    }

    // Create a DrawingVisual that contains a rectangle.
    private DrawingVisual CreateDrawingVisualRectangle()
    {
        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(160, 100), new System.Windows.Size(320, 80));
        drawingContext.DrawRectangle(System.Windows.Media.Brushes.LightBlue, null, rect);

        // Persist the drawing content.
        drawingContext.Close();

        return drawingVisual;
    }

    // Provide a required override for the VisualChildrenCount property.
    protected override int VisualChildrenCount
    {
        get { return _children.Count; }
    }



    // Provide a required override for the GetVisualChild method.
    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index >= _children.Count)
        {
            throw new ArgumentOutOfRangeException();
        }

        return _children[index];
    }
}

在画布内:

public void AddStateVisual()
{
    var sVisual = new SVisualContainer();
    Children.Add(sVisual);
    Canvas.SetLeft(sVisual, 10);
    Canvas.SetTop(sVisual, 10);
}

如何通过代码动态增加 Rectangle 的大小?我尝试设置 Rectangle 的高度和宽度,但它不起作用,使用了 ScaleTransform,但这可能不是我想要的。我需要重新绘制矩形吗?谢谢!

4

1 回答 1

1

如问题所示,我最终使用DrawingVisual了inside,并不断重绘调整大小。属性、方法和方法对此至关重要。这工作得很好,性能是可以接受的。UIElementDrawingVisualUIElement.RenderSizeUIElement.MeasureCoreUIElement.InvalidateMeasure

于 2020-09-07T17:55:00.027 回答