Home > Net >  MAUI font size auto resize according to screen (or window) width
MAUI font size auto resize according to screen (or window) width

Time:12-21

I would like all my text in MAUI UI to auto select font size according to windows width(for Windows and MacCatalyst) or screen size (for iOS and Android).

Is it correct to bind the font size to a Viewmodel(or using CodeBehind...) where I specify the font size for a set of default screen sizes (discretizing someway)? Is there a better way to do it? Is there a nuget package already doing that?

Any suggestion?

In Xamarin application I was used to use the Forms9Patch https://www.nuget.org/packages/Forms9Patch but this is not compatible with MAUI.

CodePudding user response:

Until someone writes a text auto-fitter, consider setting font size in code behind, based on window width. Here is one approach:

// ----- UTILITY CODE -----
// Target width for Portrait Tablet. Fonts full-size at this width.
public static int NominalShortEdge = 775;
// Target width for Landscape Tablet. Fonts full-size at this width.
public static int NominalLongEdge = 1280;
public static double CurrentWidth { get; private set; }
public static bool IsPortrait { get; private set; }
// "Min(1, ..": If device is wider than above specs, don't make text bigger than "full-size". Remove to let text grow even larger.
public static double FontScaleFactor => Math.Min(1, CurrentWidth / (IsPortrait ? NominalShortEdge : NominalLongEdge));

... set CurrentWidth and IsPortrait when app starts or device rotates ...


public static double CalcFontSize(double fullFontSize, double minSize = 5, double minScale = 0.3)
{
    // Limit scaling. This is used so that larger texts tend to stay larger, even on small devices.
    // Requires tweaking (elsewhere) of layout on those devices.
    // Set "minScale = 0" to remove this limit.
    var scaleFactor = Math.Max(FontScaleFactor, minScale);

    // Limit final size.
    var scaledFontSize = Math.Max(scaleFactor * fullFontSize, minSize);
    return scaledFontSize;
}


// ----- USAGE -----
const int FontSize1 = 20;
    
...
    // This can be done in view's constructor (if you don't care about auto-updating view when device rotates).
    myLabel.FontSize = CalcFontSize(FontSize1);

IMPORTANT: This assumes myLabel is in a layout that auto-sizes relative to window's width. If window is half as wide, label should be half wide, so text should be half as wide.

NOTE: The hardcoded values are for an app that is usually used on a 7" - 10" tablet; the phone implementation allows text to get quite small.
If phone is your primary target, adjust accordingly.

CodePudding user response:

I found an updated solution with this GitHub project that seems to fit my needs..

https://github.com/carolzbnbr/OnScreenSizeMarkup hope it is useful for everyone managing the same problem! Happy coding

  • Related