Home > Blockchain >  How can an image within a grid in xamarin.forms be centered
How can an image within a grid in xamarin.forms be centered

Time:07-06

I'm developing a Xamarin. Form mobile apps and trying to center and image above 2 buttons, how can I center and image in a grid XAML tag, see XAML code below in which I'm using, and having difficulty place it in the center of the mobile app screen.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DemoApp.Views.MainPage"           
             NavigationPage.HasNavigationBar="False">

    <ContentPage.Content>

        <Grid HorizontalOptions="CenterAndExpand" >
            
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
            

            <StackLayout Padding="10" HorizontalOptions="Center" VerticalOptions="Center" >
                <Image Grid.Row="0" Grid.Column="0" Source="RegisterUser" WidthRequest="100" HeightRequest="81"  HorizontalOptions="Center" VerticalOptions="Center"  />
            </StackLayout>

            <Button  Text="Sign-In" VerticalOptions="CenterAndExpand" HorizontalOptions="Center"  TextColor="White"                              
                    Grid.Row="2" Grid.Column="0"
                    BorderRadius="4" BorderWidth="1" 
                    BackgroundColor="LightGray" />
            <Button Text="Register"  TextColor="White" 
                    VerticalOptions="CenterAndExpand"
                    HorizontalOptions="Center" 
                  Grid.Row="2" Grid.Column="1"
                    BorderRadius="4" BorderWidth="1" 
                    BackgroundColor="LightGray"   />
        </Grid>

    </ContentPage.Content>
</ContentPage>

CodePudding user response:

your grid has 2 cols, so your StackLayout needs to span them in order to be centered across the entire grid

<StackLayout Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" Padding="10" HorizontalOptions="Center" VerticalOptions="Center" >
  <Image Source="RegisterUser" WidthRequest="100" HeightRequest="81" HorizontalOptions="Center" VerticalOptions="Center"  />
</StackLayout>
  • Related