【问题标题】:Changing Position of Image margin after the grid is tapped点击网格后更改图像边距的位置
【发布时间】:2018-09-03 02:46:43
【问题描述】:

所以,我试图在 UWP 中点击网格时产生涟漪效果。

对于我的 XAML 代码:

<Grid x:Name="MyGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Tapped="MyBorder_Tapped">
        <Image x:Name="MyImage" Source="ms-appx:///Assets/ripple.gif" Height="40" Width="40"/>
        <TextBlock x:Name="MyTextBlock" Text="Start"  Margin="440,230,0,0"></TextBlock> 
</Grid>

如您所见,我包含了一张图片和一段文字。我仅包含用于点击事件目的的文本。

对于 CS 代码:

private void MyBorder_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Point touchPosition = e.GetPosition(MyGrid);
            MyImage.Margin = new Thickness(touchPosition.X, touchPosition.Y, 0, 0);
            MyTextBlock.Margin = new Thickness(touchPosition.X, touchPosition.Y, 0, 0);

        }

对于TextBlock,它可以正确更改边距,但是对于图像对象,我不知道它有偏移的原因。

这是输出的示例截图:

注意:TextBlock 文本的位置是我点击网格的位置,您可以看到两者之间的偏移量。

【问题讨论】:

    标签: c# xaml uwp uwp-xaml


    【解决方案1】:

    这是因为 Image 的默认 Horizo​​nal/VerticalAlignment 设置为拉伸,如果将其更改为 Left/Top 它应该计算边距如你所愿 - 从左上角:

    <Grid x:Name="MyGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Tapped="MyBorder_Tapped">
        <Image x:Name="MyImage" Source="ms-appx:///Assets/StoreLogo.png" Height="40" Width="40" HorizontalAlignment="Left" VerticalAlignment="Top"/>
        <TextBlock x:Name="MyTextBlock" Text="Start"  Margin="440,230,0,0"></TextBlock>
    </Grid>
    

    但是您可能会考虑对此进行单独控制,也许使用一些带有偏移量的 RenderTransform 而不是操纵边距。不过,这取决于您的需求。

    应用偏移的其他方式:

    <Image x:Name="MyImage" Source="ms-appx:///Assets/StoreLogo.png" Height="40" Width="40" HorizontalAlignment="Left" VerticalAlignment="Top">
        <Image.RenderTransform>
            <TranslateTransform X="-20" Y="-20"/>
        </Image.RenderTransform>
    </Image>
    

    【讨论】:

    • 哇!太感谢了!!我不知道我还需要设置垂直和水平对齐才能设置图像的边距!但我能问最后一个问题吗?你知道我怎样才能使图像的边缘指向图像的中心,因为我认为它指向对象的左上边缘?我对吗?我尝试通过添加实际宽度 + x 和实际高度 + y 来修改边距,但仍然没有使其位于中心。有可能吗?
    • @GarryStephenson 在您的示例中,您已将图像高度/宽度硬编码为 40,因此在非常简单的情况下,您只需减去一半的值即可使图像在鼠标位置居中显示: MyImage.Margin = new Thickness(touchPosition.X - 20, touchPosition.Y - 20, 0, 0);。您也可以像在编辑的代码中一样使用 RenderTransform。
    • 您可能还想考虑在子元素上使用 Canvas 和 Canvas.Top/Canvas.Left 而不是带边距的 Grid。
    • @Romasz 非常感谢您的帮助!哈哈哈,我做的和你告诉我的完全相反,再次感谢你的代码,很乐意研究渲染转换! ^_^
    • @MichaelHawker-MSFT 会做伙计!但与此同时,我将首先研究在网格中操作项目。谢谢您的建议! ^_^
    猜你喜欢
    • 2017-01-09
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 2015-03-23
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多