如何在WPF中获取DrawingImage的正确位置

时间:2013-07-18 09:02:47

标签: wpf xaml drawing geometrydrawing

我有代码:

<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>

我希望它可以从50,50到100,50开始,但最后它从0,0到50,0开始 我StartPoint中的GeometryDrawing似乎毫无意义? 有谁知道解决方案?我不想修改Canvas.LeftCanvas.Top

2 个答案:

答案 0 :(得分:2)

显然,DrawingImage会调整到实际绘制的几何体的边界。要解决此问题,您可以将LineGeometry替换为包含点PathGeometry的{​​{1}},但不会将其绘制出来:

(0,0)

请注意<GeometryDrawing.Geometry> <PathGeometry> <PathFigure StartPoint="0,0"> <LineSegment Point="50,50" IsStroked="False"/> <LineSegment Point="100,50"/> </PathFigure> </PathGeometry> </GeometryDrawing.Geometry> 是默认值。它只是为了清晰起见。

答案 1 :(得分:0)

通过绘制一个带有透明刷子的矩形几何体,我获得了很好的效果。你可以在DrawingGroup内组成(矩形和路径)。

<Canvas>
    <Image Canvas.Left="0" Canvas.Top="0">
        <Image.Source>
            <DrawingImage>
                <DrawingImage.Drawing>

                    <DrawingGroup>

                    <GeometryDrawing Brush="Transparent"/>
                         <RectangleGeometry>
                             <!-- here you create a rectangle with desired bounds -->
                         </RectangleGeometry>
                    </GeometryDrawing>

                    <GeometryDrawing>
                        <GeometryDrawing.Pen>
                            <Pen Brush="Black" Thickness="1" />
                        </GeometryDrawing.Pen>
                        <GeometryDrawing.Geometry>
                            <LineGeometry StartPoint="50,50" EndPoint="100,50">
                            </LineGeometry>
                        </GeometryDrawing.Geometry>
                    </GeometryDrawing>

                    </DrawingGroup>

                </DrawingImage.Drawing>
            </DrawingImage>
        </Image.Source>
    </Image>
</Canvas>