Skip to content

Commit d73c966

Browse files
webwarrior-wsknocte
authored andcommitted
Core: better approximation for Label desired size
When getting desired size with constraints (0, infinity), instead of trying to fit the text by splitting it into as many lines as possible (which can lead to too much requested height), try to approximate size of a square block of text.
1 parent 6b67685 commit d73c966

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/Core/src/[Microsoft.Maui.Graphics]/Gtk/TextExtensions.cs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,21 +30,32 @@ public static double GetLineHeigth(this Pango.Layout layout, int numLines, bool
3030

3131
public static (int width, int height) GetPixelSize(this Pango.Layout layout, string text, double desiredSize = -1d, bool heightForWidth = true)
3232
{
33+
layout.SetText(text);
3334
desiredSize = double.IsInfinity(desiredSize) ? -1 : desiredSize;
3435

3536
if (desiredSize > 0)
3637
{
3738
if (heightForWidth)
3839
{
39-
layout.Width = desiredSize.ScaledToPango();
40+
if (desiredSize > 1)
41+
layout.Width = desiredSize.ScaledToPango();
42+
else
43+
{
44+
// This means layout requested desired size with constraints (0, infinity).
45+
// Instead of trying to fit the text by splitting it into as many lines as possible,
46+
// try to approximate size of a square block of text.
47+
layout.Width = -1;
48+
layout.GetPixelSize(out var singleLineWidth, out var singleLineHeight);
49+
var approximateWidth = Math.Sqrt(singleLineWidth / (singleLineHeight + 1)) * singleLineHeight;
50+
layout.Width = approximateWidth.ScaledToPango();
51+
}
4052
}
4153
else
4254
{
4355
layout.Height = desiredSize.ScaledToPango();
4456
}
4557
}
4658

47-
layout.SetText(text);
4859
layout.GetPixelSize(out var textWidth, out var textHeight);
4960

5061
return (textWidth, textHeight);

0 commit comments

Comments
 (0)