David Shochet
David Shochet

Reputation: 5375

XAML: An image is not centered correctly

In my application I need to center an image vertically and horizontally within a ListView header.

<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>

I don't understand why the black space under the image is higher than the black space above the image. I tried a Grid instead of the StackLayout with row heights 10, Auto, 10 with the same result. How can I fix that?

Upvotes: 0

Views: 164

Answers (2)

Nico Zhu
Nico Zhu

Reputation: 32775

I don't understand why the black space under the image is higher than the black space above the image.

I could not reproduce the issue by using StackLayout as root panel. The image's top margin and the bottom margin is correct. It may be that the color of the runtime tool is the same as the background color, which is a visual error. So I modify the bg color as red. For close the run time tool you could refer this link.

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

enter image description here

I tried a Grid instead of the StackLayout with row heights 10, Auto, 10 with the same result. How can I fix that?

If you use Grid as root panel, you need to notice RowSpacing property. Because the default value of this property is 6 and it will effect the layout. Please set the root grid's RowSpacing as 0 like the following.

<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

Upvotes: 1

Abdul Gani
Abdul Gani

Reputation: 689

May be the image itself has a shadow effect at the bottom. Try with a different image.

Upvotes: 0

Related Questions