-5

When using objects which contain text, such as a button or label, how can the text be dynamically sized in order to better keep text of different lengths within the viewable area?

For example if a Label within a Cell of a CircleListView of a CirclePage and the text becomes too long, it will easily fall out of view:

enter image description here

For context to what im looking for, in Android I am able to give an object either an autoSizeMinTextSize and/or autoSizeMaxTextSize tags which will automatically resize the font size based on the text length of the object. This allows text of unknown lengths to be better kept on the screen.

enter image description here

How can this be done with in a Tizen.Net application, using CircularUI elements like Button or Label or with Xamarin.Forms in general?

axa
  • 428
  • 6
  • 19

1 Answers1

1

After looking into this for a while I was able to learn of a few ways to resize text dynamically.

Take a center aligned Label:

PrimaryText = new Label
{
    FontSize = _maxFontSize,
    HorizontalTextAlignment = TextAlignment.Center,
};

Adding it to a Layout gives it access to the MeasureInvalidated event:

TextStack = new StackLayout
{
    WidthRequest = _maxWidth,
    Children = { PrimaryText }
};

Then when the text changes (among other things) the event will trigger where you can measuer the new text, compare it to the width of the stack, and then manipulate the size of font until the text fits within your layout:

TextStack.MeasureInvalidated += (sender, args) =>
{
    var primaryMeasure = PrimaryText.Measure(PrimaryText.Width, PrimaryText.Height);
    var stackMeasure = TextStack.Measure(TextStack.Width, TextStack.Height);

    if (primaryMeasure.Request.Width > stackMeasure.Request.Width)
    {
        if (PrimaryText.FontSize <= _minFontSize)
            PrimaryText.HorizontalTextAlignment = TextAlignment.Start;
        else
        {
            var fontSize = PrimaryText.FontSize - 2;
            if (fontSize < _minFontSize)
                fontSize = _minFontSize;

            PrimaryText.FontSize = fontSize;
        }
    }
};
axa
  • 428
  • 6
  • 19