XAML:图像未正确居中

时间:2018-12-17 21:51:04

标签: xaml xamarin.forms xamarin.uwp

在我的应用程序中,我需要在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>

我不明白为什么图片下方的黑色空间高于图片上方的黑色空间。我尝试用行高度为GridStackLayout10的{​​{1}}而不是Auto,结果相同。我该如何解决?

2 个答案:

答案 0 :(得分:1)

  

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

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

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

enter image description here

  

我尝试使用网格而不是StackLayout的行高为10,自动,行高为10的结果相同。我该如何解决?

如果使用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>

enter image description here

答案 1 :(得分:0)

图像本身可能在底部具有阴影效果。尝试使用其他图像。