33
votes

Here is xaml (an image in stacklayout). Everything is logical: I set Aspect to AspectFit and HorizontalOptions to FillAndExpand. Width of image must fill the width of stacklayout. Height must be calculated in order to image Aspect.

<Image BackgroundColor="Fuchsia"
       Aspect="AspectFit"
       Source="{Binding GroupLogo}"
       HorizontalOptions="FillAndExpand"
       VerticalOptions="FillAndExpand"/>

It fill the width but It doesn't want to draw image full width. Why?

enter image description here

13
use AspectFill instead of AspectFitJay Patel
@JayPatel It will cut the imageVorotnyak_Nazar

13 Answers

33
votes

AspectFit does what it says on the tin, it will fit the whole image into the View, which may leave parts of the view empty. Straight from Xamarin's documentation:

Scale the image to fit the view. Some parts may be left empty (letter boxing).

What you're looking for is AspectFill, which will scale the image to fit:

Scale the image to fill the view. Some parts may be clipped in order to fill the view.

If you are trying to get the image view to be the height of the image, I'd suggest adding a HeightRequest to the height of the image. Image controls don't seem to automatically scale in Xamarin, in my experience, as the native controls don't appear to support that by default either.

Reference

13
votes

I had a similar problem. I wanted to fill the width and the height of a StackLayout when possible but without cropping the actual image. The answers here have helped me find the correct way. Here is what has worked for me:

            <Grid 
                HorizontalOptions="FillAndExpand"
                VerticalOptions="FillAndExpand"
                 >
                <Image
                   x:Name="photo"                         
                   Aspect="AspectFit"                    
                />
            </Grid>

Maybe it will be of use for someone.

Clarification:

HorizontalOptions and VerticalOptions are with the value FillAndExpand, so the height and the width of the Grid are adjusted to fill the parent, in this case that is the Stacklayout. The image is a child of the Grid, so it transforms according to the parent (we haven't given any additional options to the image).

The aspect of the image is set to AspectFit, so that the image will fit the view (in this case the Grid) and also preserve its ratios.

In this way, if the image is in portrait mode but too narrow, it will fill the Grid's (StackLayout's) height but won't fill the width in order to preserve its ratios and to not be cropped from above or under.

If the image is in landscape mode, it will fill the Grid's (StackLayout's) width but won't fill the height in order to preserve its ratios and to not be cropped from left or right.

8
votes

As I've found no working example. This works perfectly for me:

<Grid VerticalOptions="FillAndExpand">
      <Image Source="{Binding MyImageSrc}" Aspect="AspectFill" />
</Grid>
3
votes

Up until now, the only solution I've found is to set Aspect="AspectFill" and set HeightRequest.

You can bind HeightRequest to a property and calculate the height based on the page width.

In my case the images are always the same proportion, so I do:

HeightRequest = (int)Math.Truncate(Xamarin.Forms.Application.Current.MainPage.Width / 1.41);

2
votes

Try using CachedImage from FFImageLoading NuGet package

MyPage.xaml

<StackLayout HorizontalOptions="FillAndExpand"
             VerticalOptions="FillAndExpand"
             Padding="0">
    <ff:CachedImage Source="{Binding GroupLogo}"
                    HorizontalOptions="Fill"
                    VerticalOptions="Fill"
                    Aspect="Fill"
                    DownsampleToViewSize="True"/>
</StackLayout>

This will results image trying to horizontally fill the container and to automatically generate the width while maintaining its aspect.

Add this line of code to MainActivity.xaml after global::Xamarin.Forms.Forms.Init(this, bundle);

CachedImageRenderer.Init(true);

Example can be found here

2
votes

Aspect="AspectFit" use to fit your image inside the layout it can left space if images are small. Aspect="AspectFill" used to fit your image inside the layout and it will strech your image to take full space and it will not left space either your image is small with respect of your parent layout space. So You have to use AspectFill in place of AspectFit.

1
votes

Try inclosing image inside of a grid like:

<grid>
    <image></image>
</grid>

Sometimes when I have an image that is not resizing properly, inclosing it inside a grid solves the problem.

1
votes

This requires custom rendering for both platforms. Create a FillScreenImageRenderer that inherits from ImageRenderer.

<local:FillScreenImage Source="{ImageSource}"></local:FillScreenImage>

The code below stretch to fit the entire screen. You can tweak the view bounds to fit anything you want, like, in your case, is the parent view.

iOS:

    protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
    {
        base.OnElementChanged(e);
        UIGraphics.BeginImageContext(UIScreen.MainScreen.Bounds.Size);
        Control.Image.Draw(UIScreen.MainScreen.Bounds);
        var dest = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        Control.Image = dest;
    }

Android:

    protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
    {
        base.OnElementChanged(e);
        var display = ((Activity)Context).WindowManager.DefaultDisplay;
        var b = ((BitmapDrawable)Control.Drawable).Bitmap;
        Bitmap bitmapResized = Bitmap.CreateScaledBitmap(b, display.Width, display.Height, false);
        Control.SetImageDrawable(new BitmapDrawable(Resources, bitmapResized));
    }
1
votes

I think this works. The trick is to wrap the image in a frame and bind the frame height to the image. In this example I am fitting the image to one side of a grid. hope it helps

 <Label Text="one lable" FontSize="Large"></Label>
                    <Grid  HorizontalOptions="Center"  BackgroundColor="Yellow" Margin="0"  >
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"></RowDefinition>
                        </Grid.RowDefinitions>
                        <Frame Padding="0" Margin="0"  HeightRequest="{Binding Source={x:Reference image}, Path=Height}" HasShadow="False"   Grid.Row="0" Grid.Column="0" VerticalOptions="Start" >
                            <Image x:Name="image"   Source="roth9_2.bmp" Aspect="AspectFit" ></Image>
                        </Frame>
                    </Grid>

                    <Label Text="another label" FontSize="Large"></Label>
0
votes

heightrequest of stacklayout must be either StartAndExpand or FillAndExpand or EndAndExpand in order to automatically adjust height

0
votes

It work with me

<Grid HorizontalOptions="FillAndExpand"
  VerticalOptions="FillAndExpand">
  <Image
         Aspect="AspectFill" 
         HeightRequest="255"
         WidthRequest="255">
         Source="https://pbs.twimg.com/media/DzZdI3AWkAYxH13.jpg" />
</Grid>
0
votes

I think you are out of luck, on Android at least, HeightRequest MUST be set. Just make sure that all upper layouts have an auto height adjustment.

-2
votes

You can achieve this with the use of some CSS. Note: the css parsing a little finicky in forms right now, you can't have a semi-colon at the end of the line and need to place the width call at the end of the class def...

<Image BackgroundColor="Fuchsia"
   Source="{Binding GroupLogo}"
   class="ImageFill"/>

And your related css...

.ImageFill {
    ...
    width: 100%
}