I am manually positioning labels in an AbsoluteLayout. To do this correctly I would like to know the label height prior to placing it on the UI.
I have found this solution, but not without actually placing a label:
public double MeasureLabelHeight(string text, double width, double fontSize, double lineHeight, string fontFamily)
{
Label label = new Label();
label.WidthRequest = width;
label.FontSize = fontSize;
label.LineHeight = lineHeight;
label.FontFamily = fontFamily;
label.LineBreakMode = LineBreakMode.WordWrap;
label.Text = text;
MyAbsoluteLayout.Children.Add(view: label, position: new Point(0, Height)); //place out of sight
var sizeRequest = label.Measure(widthConstraint: width, heightConstraint: double.MaxValue, flags: MeasureFlags.None);
var labelTextHeight = sizeRequest.Request.Height;
MyAbsoluteLayout.Children.Remove(label);
return labelTextHeight;
}
This solution works on UWP, I still have to test it on Android and iOS.
I would like to improve on it though. I am unable to get a correct Height value without actually placing it in the AbsoluteLayout (out of view) and am a bit worried about the overhead this probably causes with extra redraws.
I have found an old piece of code that seemingly uses native code to do this without actually placing it in the UI for iOS and Android. I'm wondering if there is a solution available that has no need for platform specific code.