Alexey Markov
Alexey Markov

Reputation: 1566

Layout background image in Xamarin.Forms

I need block with fixed height (e.g. 200) with background image, which should AspectFill this block and StackLayout with unknown height at the bottom of this block.

I tried to use RelativeLayout and put Image and StackLayout in it. Image placed perfectly, but I don't know how to place StackLayout at the bottom.

This layout containes two Labels, so I can't hard-code it's HeightConstrait and YConstrait to constant, becouse it text may have different height on different platforms and screen sizes (or, maybe, this is wrong?)

How can I do this?

enter image description here

Upvotes: 3

Views: 9494

Answers (2)

Adam
Adam

Reputation: 16199

An alternative way is with a Grid.

<Grid>
    <Image Source="..." />
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <StackLayout Grid.Row="1">    
        </StackLayout>
    </Grid>
</Grid>

While you can choose from AbsoluteLayout or a Grid, I would recommend steering clear of the RelativeLayout. It is one of the more inefficient layouts.

Upvotes: 2

App Pack
App Pack

Reputation: 1532

An Alternative I've used to the relative layout method:

This basically uses an image and a stack layout which overlap each other and filling available space. The inner stack layout is then able to expand from the end. If you want to create a "max" amount to expand upwards (eg max 50% of image), you can change the outer layout to "layoutBounds 1,1,1,.5"

The code below uses background colours so you can easily see it if copied. Plenty of options for modification eg using background images and items other than the stacklayout, eg frame.

<AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
    <Image BackgroundColor="Red" AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All" Aspect="AspectFill"></Image>
    <StackLayout AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All" BackgroundColor="Transparent">
        <StackLayout BackgroundColor="Blue" HorizontalOptions="FillAndExpand" VerticalOptions="EndAndExpand" Orientation="Vertical">
            <Label Text="Label 1"></Label>
            <Label Text="Label 2"></Label>
        </StackLayout>
    </StackLayout>
</AbsoluteLayout>

Upvotes: 6

Related Questions