UWP - 旋转图像,同时保持其与网格对齐,仅使用 XAML

2023-12-06

Using Windows 模板工作室,我创建了一个(主要是自动生成的)示例 UWP 应用程序,它在 GridView 中显示一堆图像。

为了旋转它们,我使用了以下 xaml - 注意RenderTransform我添加的块以及该范围内的注释:

<Grid x:Name="ContentArea">
    <GridView
        x:Name="ImagesGridView"
        ItemsSource="{x:Bind Source}"
        IsItemClickEnabled="True"
        Padding="{StaticResource MediumLeftRightMargin}"
        SelectionMode="None">
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="models:SampleImage">
                <Image
                    x:Name="galleryImage"
                    Style="{StaticResource ThumbnailImageStyle}"
                    Source="{x:Bind Source}"
                    AutomationProperties.Name="{x:Bind Name}"
                    ToolTipService.ToolTip="{x:Bind Name}">
                    <Image.RenderTransform> <!-- That's the part which I've added, on top of the auto-generated xaml -->
                        <RotateTransform Angle="90" CenterX="114" CenterY="114" /> <!-- because the ThumbnailImageStyle defines width and height as 228 -->
                    </Image.RenderTransform>
                </Image>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</Grid>

所以这工作得很好 - 直到我尝试非方形照片。 在此阶段,结果是图像本身有时会显示在网格内的容器之外:

note the first two images' locations, compared to where their grid item container actually is

我试过了:

  • 对 CenterX 和 CenterY 字段使用不同的值(根据网格的项目大小、根据原始图像大小,或者只是“0.5,0.5”),但这并没有解决案子。
  • To use Image.LayoutTransform (正如这里所建议的),但它似乎在通用应用程序中不可用(或者也许我缺少一些参考?)。
  • 注意到当我单击有问题的图像时,它们会突然移回网格内的预期位置(有时旋转也会消失,因此返回到原始图像)。

最终,我通过在代码隐藏中旋转图像解决了这个问题(像这儿),然后将其添加到 GridView 的绑定源中 - 但难道不应该有一种仅通过使用 xaml 本身来实现这一目标的正确方法吗?


所以这工作得很好 - 直到我尝试非方形照片。在此阶段,结果是图像本身有时会显示在网格内的容器之外:

如果你想让图像以中心旋转并且不会显示在外面GridView。你可以设置RenderTransformOrigin财产。

<Image Width="100" Height="100" RenderTransformOrigin="0.5,0.5"
Source="{Binding}">
    <Image.RenderTransform>
        <!-- That's the part which I've added, on top of the auto-generated xaml -->
        <RotateTransform Angle="90" />
        <!-- because the ThumbnailImageStyle defines width and height as 228 -->
    </Image.RenderTransform>
</Image>

enter image description here

更新 当。。。的时候GridView项目被点击,默认为Pressedvisual雕像将使gridview的内容重新布局。目前,有一个解决方法,使用GridViewItemExpanded style.

<GridView ItemContainerStyle="{StaticResource GridViewItemExpanded}"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

UWP - 旋转图像,同时保持其与网格对齐,仅使用 XAML 的相关文章

随机推荐