sgarcia.dev
sgarcia.dev

Reputation: 6150

Xamarin Forms: Image height request ignored inside frame inside relative layout

I have the following code:

<ScrollView Orientation="Vertical" Padding="0" VerticalOptions="FillAndExpand">
                <StackLayout Spacing="0" Padding="15,0">
                    <Frame HasShadow="false" BackgroundColor="Transparent" Padding="0">
                        <RelativeLayout BackgroundColor="Olive" Padding="0" VerticalOptions="End">
                            <Frame HeightRequest="100" WidthRequest="100" BackgroundColor="Purple" Padding="0" HasShadow="false">
                                <Image HeightRequest="50" WidthRequest="50" Source="assets/avatar-man.png"></Image>
                            </Frame>
                            <BoxView HeightRequest="100" BackgroundColor="Teal" RelativeLayout.XConstraint="{ConstraintExpression Type=Constant, Constant=100}" RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1, Constant=-100}" />
                            <Frame BackgroundColor="Transparent" HasShadow="false" Padding="0" RelativeLayout.XConstraint="{ConstraintExpression Type=Constant, Constant=100}" RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1, Constant=-100}">
                                <Label>Hello</Label>
                            </Frame>
                        </RelativeLayout>
                    </Frame>
                </StackLayout>
            </ScrollView>

However, for some reason the Image height request gets ignored and instead of showing a 50x50 unit square, it fills the entire screen like this:

Issue Image

Does anyone know why this gets ignored and how to fix this?

Upvotes: 10

Views: 28084

Answers (2)

cfly24
cfly24

Reputation: 1952

I usually just set a Margin on the Image, like so:

<Frame HeightRequest="100" WidthRequest="100" BackgroundColor="Purple" Padding="0" HasShadow="false">
    <Image Margin="25" VerticalOptions="Center" Source="assets/avatar-man.png"></Image>
</Frame>

Just take the size (height or width) of the Frame, subtract the size of the Image, and divide by 2. This will set the image size to 50.

Easy way to do it if the size of the frame won't change.

Upvotes: 1

Niels
Niels

Reputation: 1716

I had the same issue, I ended up wrapping a StackLayout around my image like this:

<StackLayout>
  <Image Source="{Binding MyImage}" WidthRequest="50" HeightRequest="50"/>
</StackLayout>

Upvotes: 28

Related Questions