Search code examples
wpfxamldrawinggeometrydrawing

How to get correct position of DrawingImage in WPF


I have the code:

<Canvas>
    <Image Canvas.Left="0" Canvas.Top="0">
        <Image.Source>
            <DrawingImage>
                <DrawingImage.Drawing>
                    <GeometryDrawing>
                        <GeometryDrawing.Pen>
                            <Pen Brush="Black" Thickness="1" />
                        </GeometryDrawing.Pen>
                        <GeometryDrawing.Geometry>
                            <LineGeometry StartPoint="50,50" EndPoint="100,50">
                            </LineGeometry>
                        </GeometryDrawing.Geometry>
                    </GeometryDrawing>
                </DrawingImage.Drawing>
            </DrawingImage>
        </Image.Source>
    </Image>
</Canvas>

I hope it can be a line start from 50,50 to 100,50, but finally it starts with 0,0 to 50,0 I seems StartPoint in GeometryDrawing makes no sense? Does anyone know the solution? I don't want to modify Canvas.Left and Canvas.Top.


Solution

  • Apparently a DrawingImage is adjusted to the bounds of the actually drawn geometry. To get around that, you may replace the LineGeometry by a PathGeometry that contains the point (0,0), but does not draw it:

    <GeometryDrawing.Geometry>
        <PathGeometry>
            <PathFigure StartPoint="0,0">
                <LineSegment Point="50,50" IsStroked="False"/>
                <LineSegment Point="100,50"/>
            </PathFigure>
        </PathGeometry>
    </GeometryDrawing.Geometry>
    

    Note that StartPoint="0,0" is the default value. It's just here for clarity.