如何以编程方式调整 DrawingVisual 的大小?

问题描述 投票:0回答:1

所以,我是 WPF 绘图新手。出于性能原因,我不得不从 ContentControl 和 UserControl 等常规控件切换到 DrawingVisual 等更轻量级的元素。我正在开发一个图表应用程序,画布上最多可能有 1000 个元素,可以拖动、调整大小等。首先,使用DrawingVisual而不是Shape更好吗? 其次,我的主要问题在这里。我将 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);
}

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

c# wpf drawingcontext drawingvisual
1个回答
1
投票

我最终在

DrawingVisual
内使用了
UIElement
,如问题所示,并在调整大小时不断重绘
DrawingVisual
UIElement.RenderSize
属性、
UIElement.MeasureCore
方法和
UIElement.InvalidateMeasure
方法是其中的核心。这工作得很好,性能是可以接受的。

© www.soinside.com 2019 - 2024. All rights reserved.