Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a background image with XAML/.NET Maui that has AspectFill behavior but left aligned?

I am working an app that uses an image as its background, and I want it to fill the entire window regardless of size. The image source is square-ish, like this:

Still Life Square Aspect Ratio

The simplest way to do this is using AspectFill like this:

<Image 
     Source="image_source.png"
     Aspect="AspectFill"/>

But that results in the image being centered, like this:

Still Life Centered Vertical Crop

When what I need is for the image to be left aligned, like this:

Still Life Left Aligned Vertical Crop

I almost had some success using this:

<AbsoluteLayout>
        <Image 
            Source="image_source.png" 
            AbsoluteLayout.LayoutFlags="HeightProportional"
            AbsoluteLayout.LayoutBounds="0,0,Autosize,1"/>       
</AbsoluteLayout>

but the problem there became when I had a screen like a tablet or foldable which is wider horizontally, it ended up getting letterboxed like this:

Still Life letterboxed

When what I would want would just be a regular AspectFill like this:

Still Life Wide AspectFill

Is there any way to get this behavior with the existing Aspect options? If not, is there a way to extend the Aspect enum and the Renderer to make the image perform the same as AspectFill, but locked to the left edge of the image instead of the center?

I'm using XAML with .NET Maui, so if there is a solution in C# I'm open to that too

like image 416
James Bartlett Avatar asked Dec 06 '25 17:12

James Bartlett


1 Answers

Was able to get a solution from Reddit, so I'm posting it here for anyone who stumbles across this:

My final XAMl ended up being

<Grid>
    <Image
        x:Name="backgroundImage"
        Source="image_source.png"
        Aspect="AspectFill"
        HorizontalOptions="Start"/>
</Grid>

And I added this to the code-behind:

protected override void OnSizeAllocated (double pageWidth, double pageHeight) {
    base.OnSizeAllocated(pageWidth, pageHeight);
    const double aspectRatio = 1600 / 1441.0; // Aspect ratio of the original image
    backgroundImage.WidthRequest = Math.Max(pageHeight * aspectRatio, pageWidth);
}
like image 183
James Bartlett Avatar answered Dec 08 '25 09:12

James Bartlett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!