UWP C# - Font auto size of TextBlock and RichTextBlock

218 Views Asked by At

How to force TexBlock and RichTextBlock to change FontSize so that the text fits in the window. When changing the text, if the text is too large, then it does not fit in the window. How to make it fit completely?

viewBox is not suitable because "TextWrapping=Wrap" does not work in it

Update: I have a TextBlock for the entire width and height of the window. The user can change the text of any length. I would like to force TextBlock to change FontSize so that all the text fits in the window. viewBox is not suitable because "TextWrapping=Wrap" does not work in it.

I wrote a temporary code. But it's a terrible code. I would like to find a more correct code:

        var textBlockHeight = Convert.ToInt32(page.ActualHeight - textBlock.Margin.Bottom);
        var textBlockWidth = Convert.ToInt32(page.ActualWidth - (textBlock.Margin.Right * 2));

        var canvas = new CanvasTextFormat
        {
            FontSize = 150,
            WordWrapping = CanvasWordWrapping.Wrap,
        };

        var device = CanvasDevice.GetSharedDevice();
        var layout = new CanvasTextLayout(device, text, canvas, textBlockWidth, 0);
        var textHeight = (int)layout.DrawBounds.Height;


        while (textBlockHeight < textHeight)
        {
            layout = new CanvasTextLayout(device, text, canvas, textBlockWidth, 0);
            textHeight = (int)layout.DrawBounds.Height;

            canvas.FontSize--;

            if (canvas.FontSize <= 3)
            {
                break;
            }
        }

        textBlock.FontSize = canvas.FontSize;
        textBlock.Text = text;
0

There are 0 best solutions below