Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top align an aspect filled image in Xamarin Forms

Update: I have simplified the example and code and provided an image

I have a stack layout containing two images. The first image is just to show the entire image. The second image has a fixed height and image aspect is set to AspectFill. I see the middle part of the second image but would like to see the top part. Is there any way I can achieve this?

Here is the XAML

<StackLayout Spacing="20">

    <Image Source="darth.jpg" />

    <Image Source="darth.jpg"
           HeightRequest="100"
           Aspect="AspectFill" />

</StackLayout>

Here is what it looks like. I want the second image to show the top part of the image, not the middle part.

enter image description here

like image 201
Steve Chadbourne Avatar asked Feb 28 '16 20:02

Steve Chadbourne


2 Answers

If you set the HeightRequest on the Image, that will cause Xamarin.Forms to do the clipping, and there doesn't seem to be anything you can do about it. However if you wrap it in a ScrollView with a HeightRequest of 100, it will render as you want:

var image = new Image()
{
    Source = "darth.jpg",
    Aspect = Aspect.AspectFill
};
var imageWrap = new ScrollView()
{
    HeightRequest = 100,
    Content = image
};

This has the added functionality that the user will be able to scroll through the image. Depending on the context, this may not be desirable. Plus, according to Xamarin documentation:

ScrollViews should not be nested. ScrollViews should not be nested with other controls that provide scrolling, like ListView and WebView.

like image 169
DavidS Avatar answered Sep 23 '22 19:09

DavidS


There's no code in Xamarin.Forms Image implementation, which adjusts the position of image with Aspect.AspectFill, so you have two options here:

  1. Try to add an extra wrap with HeightRequest="100" around the second image, and remove HeightRequest="100" and Aspect="AspectFill" from it.
  2. Implement your own ImageRenderer for the target platform following this guide.
like image 43
outring Avatar answered Sep 22 '22 19:09

outring