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

UWP - Rotating an Image while keeping it aligned to the grid, using XAML only

使用 Windows Template Studio,我创建了一个(主要是自动生成的)示例 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>

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

我试过:

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

So that worked fine - until I tried non-square photos. At this stage, the result was that the image itself would sometimes show outside of its container within the grid:

如果你想要图像以中心旋转并且它不会显示在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>

更新 当点击GridView项时,默认的Pressed visual雕像会使gridview的内容重新布局。目前,有一个使用 GridViewItemExpanded 样式的解决方法。

<GridView ItemContainerStyle="{StaticResource GridViewItemExpanded}"