首页 > 解决方案 > XAML:图像未正确居中

问题描述

在我的应用程序中,我需要在ListView标题中垂直和水平居中图像。

<ListView x:Name="MenuItemsListView"
          SeparatorVisibility="None"
          HasUnevenRows="true" 
          ItemsSource="{Binding MenuItems}">      
    <ListView.Header>
        <StackLayout BackgroundColor="Black" HeightRequest="100">
            <Image HeightRequest="80" HorizontalOptions="CenterAndExpand" 
                   VerticalOptions="CenterAndExpand" Source="Assets\logo.png" />
        </StackLayout>
    </ListView.Header>
</ListView>

我不明白为什么图像下方的黑色空间高于图像上方的黑色空间。我尝试了 aGrid而不是StackLayoutwith row heights 10, Auto10结果相同。我该如何解决?

标签: xamlxamarin.formsxamarin.uwp

解决方案


我不明白为什么图像下方的黑色空间高于图像上方的黑色空间。

我无法通过StackLayout用作根面板来重现该问题。图像的上边距和下边距正确。可能是运行时工具的颜色和背景颜色一样,是视觉上的错误。所以我将bg颜色修改为红色。要关闭运行时工具,您可以参考此链接

<StackLayout BackgroundColor="Black" HeightRequest="100">
  <Image HeightRequest="80" HorizontalOptions="CenterAndExpand" 
    VerticalOptions="CenterAndExpand" Source="Assets\logo.png" />
</StackLayout>

在此处输入图像描述

我尝试了行高为 10、Auto、10 的 Grid 而不是 StackLayout,结果相同。我该如何解决?

如果您使用 Grid 作为根面板,则需要注意RowSpacing属性。因为这个属性的默认值为6,会影响布局。请将根网格的 RowSpacing 设置为 0,如下所示。

<Grid BackgroundColor="Red" HeightRequest="100" RowSpacing="0" >
    <Grid.RowDefinitions>
        <RowDefinition Height="10"/>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="10"/>
    </Grid.RowDefinitions>
    <BoxView Grid.Row="0" BackgroundColor="Black" VerticalOptions="FillAndExpand"  />
    <Image Grid.Row="1" HeightRequest="80" HorizontalOptions="CenterAndExpand" 
   VerticalOptions="CenterAndExpand" Source="Assets\bc1.jpg" />
    <BoxView  Grid.Row="2" BackgroundColor="Blue" VerticalOptions="FillAndExpand" />
</Grid>

在此处输入图像描述


推荐阅读