DrawingContext.DrawRectangle绘制一个rect

时间:2016-03-30 01:43:12

标签: wpf drawingcontext

我试图在图片中绘制一个矩形:

<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)处绘制。我怎么了?

1 个答案:

答案 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();