I am trying to calculate the height needed by a text programmatically, so I am using StaticLayout.
I was experimenting with a Label (TextView) using its paint object, to make sure the height calculated is the same as TextView's height rendered by Android.
It works good for single-line text both in Arabic and English, and works for mutli-line text in English, but Arabic height is off, it is always shorter than what Android renders.
The top height ~80 is what the TextView's height is, while the latter ~75 is the calculated height needed.
Since that it works fine in English, I guess I might need to set some other property or something, but I cannot tell what.
Following is my code, it is in C# since I am using Xamarin, but it should be clear for Android developers.
Control
is TextView.
double getTextHeight(string str, double widthConstraint)
{
if (Control == null || String.IsNullOrWhiteSpace(str))
return 0;
var builder = StaticLayout.Builder.Obtain(str, 0, str.Length, Control.Paint, (int)widthConstraint);
builder.SetAlignment(Control.Layout.GetAlignment());
builder.SetIncludePad(true);
builder.SetLineSpacing(Control.Layout.SpacingAdd, Control.Layout.SpacingMultiplier);
builder.SetBreakStrategy(Control.BreakStrategy);
builder.SetJustificationMode(Control.JustificationMode);
builder.SetHyphenationFrequency(Control.HyphenationFrequency);
var staticLayout = builder.Build();
return staticLayout.Height;
}
This is the code I was missing, it is working like charm :)
builder.SetUseLineSpacingFromFallbacks(true);