如何在Canvas中移动Image而不将其绑定到它所属的外部Grid?

时间:2013-03-04 17:50:40

标签: c# wpf image canvas grid

我想在我正在制作的基于磁贴的游戏中将图像放置在某个磁贴的顶部。问题是,当我生成随机地图时,当绘制Canvas的Rectangle子项时,它会在Image上绘制。我通过放置窗口外部网格的图像部分来解决这个问题。问题是,当我想将Image放在Canvas中的某个Rectangle上时,由于Grid比Canvas大,所以坐标是关闭的。如何将图像边距限制为仅限于画布(画布边框作为限制),而不是将网格边框限制为限制?

E.g。给图像一个Margin.Left = 50的值会将它放在画布中的完美位置,但由于它的比例较大,它将被放置在网格中的不同位置。

// Image displays, but does not display when I add child Rectangles to the Canvas
<Canvas Height="700" HorizontalAlignment="Left" Name="canvas1" VerticalAlignment="Top" Width="700">
        <Image Name="heroImage" Stretch="Fill" Source="hero.png" Height="74" Canvas.Left="558" Canvas.Top="602" />
</Canvas>



<Grid>
    <Canvas Height="700" HorizontalAlignment="Left" Name="canvas1" VerticalAlignment="Top" Width="700">
        // Removed the Image
    </Canvas>

    // Placed the Image outside the Canvas, but now it will draw according to the Grid's Margin limits and not the Canvas Margin limits
    <Image Name="heroImage" Stretch="Fill" Source="hero.png" Height="74" Canvas.Left="558" Canvas.Top="602" />
</Grid>

Image position inside Canvas 画布内的图像,位置完美

Image position outside the Canvas in the Grid 自从我使用Canvas Margin坐标以来,网格中的图像被错误地放置了

2 个答案:

答案 0 :(得分:1)

你做的第一种方式很好,你的形象应该是Canvas的一个孩子做Canvas.Left ......

要解决您的问题,您可以将图像放在所有其他矩形的顶部,使用ZIndex吗?

Canvas.ZIndex="3 or whatever"

值为2的图像绘制在值为1的矩形上。因此,您可以使用高数字...

答案 1 :(得分:1)

我认为您可以在Canvas中使用您的图像,如果您想要将图像放在Rectangle上,则需要将图像(Palen.ZIndex或Canvas.ZIndex)属性设置为大于Rectangles。 例如:

<Canvas Height="700" HorizontalAlignment="Left" Name="canvas1" VerticalAlignment="Top" Width="700">
        <Image Name="heroImage" Stretch="Fill" Source="hero.png" Height="74" Canvas.Left="558" Canvas.Top="602" Canvas.ZIndex="1000" />
        <Rectangle x:Name="Some Rectangle" Canvas.ZIndex="1"/>
</Canvas>

图像将显示在矩形上方。我认为这是解决方案。将图像放在画布上可能会非常复杂,无法设置您想要的位置。