Home > Software engineering >  Background image getting squeezed in Xamarin app
Background image getting squeezed in Xamarin app

Time:03-10

I have a background image on my login page in my Xamarin Forms 5 app.

I want this image to take up the whole background but NOT get squeezed so that I can keep its original ratio. Otherwise, the image gets distorted. Currently, it takes up the whole page but it's getting squeezed vertically. How do I make sure the image maintains its original aspect ratio and not get squeezed?

Here's my XAML code on this page:

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="400" />
            <RowDefinition Height="200" />
        </Grid.RowDefinitions>

        <!-- Logo -->
        <Image Grid.Row="0"
               Source="my_background_image.png"
               HorizontalOptions="FillAndExpand"
               VerticalOptions="FillAndExpand"
               HeightRequest="150"/>

        <!-- Sign In Button -->
        <StackLayout Grid.Row="1" Padding="10,0,10,0" VerticalOptions="Center">
            <Button VerticalOptions="Center" Text="Sign In  /  Sign Up" Clicked="Login_Tapped"/>
        </StackLayout>
    </Grid>

CodePudding user response:

I don't know whether or not you set the background image with the property named BackgroundImageSource of the ContentPage. I had tried this and the picture showed well.

If you had tried that and didn't get a satisfactory effect, you can add a Image view into the Grid as the background.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="400" />
        <RowDefinition Height="200" />
    </Grid.RowDefinitions>
    <Image
        Grid.RowSpan="3"
        Aspect="AspectFill"
        Source="background.jpg" />
    <!-- Logo -->
    <Image Grid.Row="0"
           Source="my_background_image.jpg"
           HorizontalOptions="FillAndExpand"
           VerticalOptions="FillAndExpand"
           HeightRequest="150"/>

    <!-- Sign In Button -->
    <StackLayout Grid.Row="1" Padding="10,0,10,0" VerticalOptions="Center">
        <Button VerticalOptions="Center" Text="Sign In  /  Sign Up" Clicked="Login_Tapped"/>
    </StackLayout>
</Grid>

If the aspect ratio of your picture is too big, you can change the Aspect="AspectFill" to Aspect="AspectFit".

  • Related