Xamarin Forms Image with 100% of parent container width and auto Height to maintain aspect ratio - xaml

Is it possible to have an Image take 100% width of its parent container while actually fitting the whole image within this container without clipping, and while having height automatically adjusted to preserve aspect ratio?
I have read similar questions both on SO and Xamarin Forums but apparently this cannot be done without implementing custom renderers or manually calculating correct sizes in code. But to calculate this in code you would need either image dimensions or aspect ratio. For applications where neither of these are known before head, this is a problem.
In terms of CSS, the solution I am looking for is similar to having
width:100%; height:auto;
Implementing a custom renderer for such a trivial task is an overkill and a huge embarrassment for Xamarin in my opinion; unless I am understanding something wrong.

I have searched for an answer to this problem for a long time. As others have noted, I did not find a Xaml-only solution. I choose a different route and present my solution for those who might find it instructive and as the seed for changes to FFImageLoading to solve this correctly.
I created a subclass of CachedImage and overrided OnMeasure. In order for CachedImage.OnMeasure to work in the aspect modes (not fill mode), it has to return a SizeRequest which matches the ratio of the underlying image. So the solution I chose was simply to use the provided widthConstraint and calculate the height as widthConstraint / ratio. This description only addresses one of the many cases: where the widthConstraint is not infinity and the desire is to answer the specific question posed here (width of 100% and auto height).
A subclass which implements this case:
public class CachedImage2 : CachedImage
{
protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
{
var sr = base.OnMeasure(widthConstraint, heightConstraint);
if (sr.Request.IsZero)
return sr;
var ratioWH = sr.Request.Width / sr.Request.Height;
var sr2 = new SizeRequest(new Size(widthConstraint, widthConstraint / ratioWH));
return sr2;
}
}

I was unable to find a pure XAML solution to this problem and therefore decided to use ffimageloading's Success event to find out the original width and height of loaded image and get aspect ratio from these values, store it, and use it in SizeAllocated event to maintain aspect ratio of the image while making sure its width is 100% of the parent container.
Sample code:
private void testImage_OnSuccess(object sender, CachedImageEvents.SuccessEventArgs e)
{
var image = sender as CachedImage;
double width = e.ImageInformation.OriginalWidth;
double height = e.ImageInformation.OriginalHeight;
ratio = width / height; // store it in a variable
}
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (this.Width > 0 && ratio != 0) // width of the parent container
testImage.HeightRequest = this.Width / ratio;
}

Presuming when you say:
and while having height automatically adjusted..
You mean the height of the container.
Yes this is completely possible in Xamarin.Forms.
Let's imagine I have a Grid as my parent container. Here is how I would do it.
<!-- remove all the padding & margin & spacing on Grid -->
<Grid RowSpacing="0"
ColumnSpacing="0"
Margin="0"
Padding="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <!-- the containers height will now adjust -->
<RowDefinition Height="56"/> <!-- This one is for the other content in your view etc -->
</Grid.RowDefinitions>
<!-- Put your image inside your parent container and apply properties -->
<Image Source="some_source.png"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"/>
</Grid>
The Horizontal and vertical options are as if you are setting width:100% and height: 100% in CSS.

Put you Image in a frame. And then set the height and width of image accprding to the frame.
<Frame>
<Image></Image>
</Frame>
You could change the width and height according to your frame via binding Value Converters.
Binding Value Converters: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/converters
Set the name to your Frame first.
<Frame
…………
x:Name="frame"/>
Create the MyConverter. You could change the percentage of value in Convert method.
MyConverter.cs
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Set the StaticResource.
<ContentPage.Resources>
<ResourceDictionary>
<local:MyConverter x:Key="MyConverter" />
</ResourceDictionary>
Binding to your image.
<Image WidthRequest="{Binding Source={x:Reference frame},Path=Width,Converter={StaticResource MyConverter}}"
HeightRequest="{Binding Source={x:Reference frame},Path=Height,Converter={StaticResource MyConverter}}"></Image>

Related

UWP: how to get element size before painting

My code will draw a graphic and, before the paint event, I need to set the size of element containing the graphic. In part, this comes from a value in an XAML file:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="35" />
</Grid.RowDefinitions>
...
</Grid>
During the view initialization, I'm hoping to be able to modify the graphic width based on some other factors, but I need the height value, from XAML.
At a breakpoint, I can view the various View values, and at this point ActualHeight and ActualWidth are still 0. I don't see anything else I could use.
Is there another event, coming before paint, that I could use ?
The answer is to use SizeChanged event.
In XAML, for example:
<skia:SKXamlCanvas
x:Name="EICanvas"
SizeChanged="OnSizeChanged" />
And in code-behind:
private void OnSizeChanged (Object sender, SizeChangedEventArgs e)
{
var newH = e.NewSize.Height;
var oldH = this.ActualHeight; // in pixels
...
}

How to switching between InkCanvas and Canvas in UWP

I'm struggling with new UWP InkCanvas for my apps.If you are familiar with the new InkCanvas in UWP, I would truly appreciate your help.
I have a UWP apps need to switching between InkCanvas and Canvas, which I wish to use InkCanvas for Drawing, Canvas for creating Contents such as RichEditbox, Image, etc...
My XAML is below
<Grid Margin="100,0,100,0" Background="White" x:Name="MainGrid" PointerMoved="MyCanvas_PointerMoved" PointerReleased="MyCanvas_PointerReleased" PointerPressed="MyCanvas_PointerPressed">
<Canvas x:Name="MyCanvas" />
<InkCanvas x:Name="inkCanvas" Canvas.ZIndex="0" />
<!-- End "Step 2: Use InkCanvas to support basic inking" -->
</Grid>
I tried to make my Canvas ZIndex greater than InkCanvas by using
private void AppBarButton_Click(object sender, RoutedEventArgs e)
{
if(Canvas.GetZIndex(MyCanvas) > 1)
{
Canvas.SetZIndex(MyCanvas, 0);
}
else
{
Canvas.SetZIndex(MyCanvas, 5);
}
}
However I can't make my Canvas come to the front, the InkCanvas keep Capturing my stroke if I Draw on it instead.
Does anyone know how to switch the Canvas and InkCanvas in my Grid without changing the Visibility of my InkCanvas to Collapsed?
By default the Canvas background is empty (null), so it will not capture pointer input and will pass it through to the InkCanvas.
If you want to prevent this, you could set its Background to Transparent.
However, when you start putting some controls on the Canvas itself, they should capture the pen input and not let it through to the InkCanvas.

XAML : Binding FontSize to the Height of Control

Within a Xamarin.Form page, I am trying to bind the FontSize of a label to the height of that same label.
I seen examples in WPF that do this:
FontSize="{Binding ElementName=CurrentPresenter, Path=Height}"
But I can not seem to get anything to work like that in Forms, i.e.:
<Label
Text="X"
FontSize="{Binding ElementName=CurrentPresenter, Path=RequestedHeight}"
HorizontalTextAlignment="Center"
AbsoluteLayout.LayoutBounds="0.1, 0.5, 0.33, 0.66"
AbsoluteLayout.LayoutFlags="All" />
(I will use a data converter to adjust the font size so based upon screen DPI, I can auto-adjust, but for now, I'm just trying to bind it to a control's height to get something other than default system font size)
This way appears to work fine, not sure about the runtime layout performance though...
FYI: This does not work within the XAML Designer, only runtime
<Label
Text="X"
x:Name="foo"
BindingContext="{x:Reference Name=foo}"
FontSize="{Binding Path=Height}"
HorizontalTextAlignment="Center"
AbsoluteLayout.LayoutBounds="0.1, 0.5, 0.33, 0.66"
AbsoluteLayout.LayoutFlags="All" />
Not exactly related to OP question but searching "Xaml height based on another control" has hardly any results in Google so posting this in case it helps someone else.
To change the size of smaller buttons to match the size of a larger button like in the following picture
There are several ways to do this without using code behind but if the layout you are trying to use is being difficult here following is another option. To change the size of the smaller buttons without changing the binding of those controls you can give the buttons names in XAML and then do something like this in the code behind:
public HomeOpenPage ()
{
InitializeComponent ();
RefreshButton.PropertyChanging += RefreshButton_PropertyChanging;
}
private void RefreshButton_PropertyChanging(object sender, PropertyChangingEventArgs e)
{
if (RefreshButton.Width != -1)
{
var width = RefreshButton.Width;
CSVButton.WidthRequest = width;
EndButton.WidthRequest = width;
}
}
protected override void OnDisappearing()
{
RefreshButton.PropertyChanging -= RefreshButton_PropertyChanging;
base.OnDisappearing();
}

MeasureOverride does not work on Canvas

I need to change Rectangle size placed on Canvas, so I inherited Canvas class to use MeasureOverride:
public class CustomCanvas : Canvas
{
public CustomCanvas() : base(){}
protected override Size MeasureOverride(Size availableSize)
{
Size canvasDesiredSize = new Size();
foreach (UIElement child in Children)
{
child.Measure(new Size(300, 300));
canvasDesiredSize = child.DesiredSize;
}
return canvasDesiredSize;
}
}
And used it:
<local:CustomCanvas Width="500" Height="800" Background="Gray">
<Rectangle Fill="AliceBlue" Height="100" Width="100"/>
</local:CustomCanvas>
But after execution the rectangle still 100,100 size (as specified in XAML). When child.Measure(new Size(300, 300)); executed child.DesiredSize shows 0,0. Something strange happens there.
I used this as reference.
The short answer is that Width and Height override any size given in Measure().
Microsoft's documentation lacks important information regarding the data flow between Measure() and MeasureOverride().
The container calls Child.Measure()
Measure() calls MeasureCore()
MeasureCore() calls MeasureOverride()
Measure is a method of UIElement.
MeasureCore is a method of FrameworkElement, which inherits from UIElement. MeasureOverride is a method of FrameworkElement. MeasureOverride gets overridden by the child.
UIElement.Measure(avialableSize) does the following before calling MeasurementCore():
throws exception if avialableSize IsNan, both for width and height
if UIElement is collapsed, MeasureCore will not get called
if the availableSize has not changed, MeasureCore will not get called, unless InvalidateMeasure was called before
call InvalidateArrange
FrameworkElement.MeasurementCore(availableSize) does the following before calling MeasureOverride():
removes Margin from availableSize
enforces height, minHeight and maxHeight over availableSize and the same for the witdh properties
after calling MeasureOverride(), MeasurementCore() adjusts the values returned by MeasureOverride() to calculate DesiredSize:
DesiredSize must be within MinWidth and MaxWidth
add margin to DesiredSize
after calling FrameworkElement.MeasurementCore(), UIElement.Measure() executes:
throws exception if return width or height is Infinite
throws exception if return width or height isNaN

XAML: accessing actual width and height

I have a viewbox with an image inside:
<Viewbox MaxHeight="100" MaxWidth="100" x:Name="Scenario4ImageContainer2" Stretch="Uniform" Grid.Column="1" Grid.Row="1">
<Image x:Name="Scenario4Image" PointerPressed="Scenario4Image_PointerPressed" HorizontalAlignment="Stretch" />
</Viewbox>
I want to be able to grab the actual width/height values, but when I try this in the backend C#:
int w = (int)Scenario4ImageContainer.Width
I get an error saying the parameter is incorrect.
This goes away if I hardcode the width, but I want it to resize dynamically.
I also tried grabbing Scenario4ImageContainer.ActualWidth but this parameter was "incorrect" as well.
A while back I was trying to measure width of a string. You can try a similar mechanism to get dimensions.
http://invokeit.wordpress.com/2012/09/19/how-to-measure-rendered-string-dimensions-in-win8dev/
this.tb.FontSize = 20;
this.tb.Measire(new Size(400, 300)); // assuming that 400x300 is max size of textblock you want
double currentWidth = this.tb.DesiredSize.Width;
double currentHeight = this.tb.DesiredSize.Height;
Seems like I've found the event you need to handle: you should handle ImageOpened event. It is because image is retrieved asynchronously and if try to handle any other event there is a good chance to not have image loaded at that time so actual size is zero
On every draw I do a quick check to see if the container size has changed (with an initialization of 0 at the beginning to make sure it catches the first time).
if (containerWidth != Output.ActualWidth - 300)
{
Scenario4ImageContainer.Width = Output.ActualWidth - 300;
Scenario4ImageContainer.Height = Output.ActualHeight - 20;
containerWidth = Output.ActualWidth - 300;
}
It works for the most part, but when the class gets navigated out and navigated back it has a problem for some reason. Probably unrelated.