Skip to content

Commit

Permalink
Core: better approximation for Label desired size
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
webwarrior-ws authored and knocte committed Jun 10, 2024
1 parent 6b67685 commit d73c966
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/Core/src/[Microsoft.Maui.Graphics]/Gtk/TextExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,21 +30,32 @@ public static double GetLineHeigth(this Pango.Layout layout, int numLines, bool

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

if (desiredSize > 0)
{
if (heightForWidth)
{
layout.Width = desiredSize.ScaledToPango();
if (desiredSize > 1)
layout.Width = desiredSize.ScaledToPango();
else
{
// This means layout requested desired size with constraints (0, infinity).
// Instead of trying to fit the text by splitting it into as many lines as possible,
// try to approximate size of a square block of text.
layout.Width = -1;
layout.GetPixelSize(out var singleLineWidth, out var singleLineHeight);
var approximateWidth = Math.Sqrt(singleLineWidth / (singleLineHeight + 1)) * singleLineHeight;
layout.Width = approximateWidth.ScaledToPango();
}
}
else
{
layout.Height = desiredSize.ScaledToPango();
}
}

layout.SetText(text);
layout.GetPixelSize(out var textWidth, out var textHeight);

return (textWidth, textHeight);
Expand Down

0 comments on commit d73c966

Please sign in to comment.