DrawingContext.DrawRectangle 绘制一个矩形

DrawingContext.DrawRectangle to draw a rect

我正在尝试将矩形绘制到图像中:

<Canvas>
    <Image>
        <Image.Source>
            <DrawingImage>
                <DrawingImage.Drawing>
                    <DrawingGroup x:Name="_drawingGroup" />
                </DrawingImage.Drawing>
            </DrawingImage>
        </Image.Source>
    </Image>
</Canvas>

C# 代码如下所示:

DrawingVisual visual = new DrawingVisual();
using (DrawingContext dc = visual.RenderOpen())
{
    Rect rect = new Rect(new Point(100, 100), new Size(200, 100));
    dc.DrawRectangle(Brushes.Blue, null, rect);
}

this._drawingGroup.Children.Add(visual.Drawing);
this._drawingGroup.Freeze();

如您所见,我打算绘制一个左上角 (100,100) 的矩形。但它没有按预期工作 - 它总是在 (0,0) 处绘制。我怎么了?

DrawingImage 将其 Drawing 与绘图的可见 Bounds 对齐。

作为解决方法,您可以添加一个原点为 (0, 0) 的透明矩形。另请注意,您不需要 DrawingVisual 来创建绘图:

drawingGroup.Children.Add(new GeometryDrawing(
    Brushes.Transparent, null,
    new RectangleGeometry(new Rect(0, 0, 1, 1))));

drawingGroup.Children.Add(new GeometryDrawing(
    Brushes.Blue, null,
    new RectangleGeometry(new Rect(100, 100, 200, 100))));

drawingGroup.Freeze();

带有 DrawingImage 的 Image 控件的替代方法可能是带有 DrawingBrush 的(足够大的)Rectangle:

<Rectangle Width="10000" Height="10000">
    <Rectangle.Fill>
        <DrawingBrush ViewboxUnits="Absolute" Viewbox="0,0,10000,10000">
            <DrawingBrush.Drawing>
                <DrawingGroup x:Name="drawingGroup" />
            </DrawingBrush.Drawing>
        </DrawingBrush>
    </Rectangle.Fill>
</Rectangle>

现在您可以按照预期创建绘图:

drawingGroup.Children.Add(new GeometryDrawing(
    Brushes.Blue, null,
    new RectangleGeometry(new Rect(100, 100, 200, 100))));

drawingGroup.Freeze();