xamarin MAUI字体大小根据屏幕(或窗口)宽度自动调整大小

uxh89sit  于 2022-12-25  发布在  其他
关注(0)|答案(2)|浏览(598)

我想我的所有文本在MAUI用户界面自动选择字体大小根据窗口宽度(Windows和MacCatalyst)或屏幕大小(iOS和Android)。
将字体大小绑定到Viewmodel(或者使用CodeBehind ...),在Viewmodel中为一组默认屏幕大小指定字体大小(某种程度上离散化),这样做正确吗?有没有更好的方法?有没有nuget包已经在做这件事?
有什么建议吗?
在Xamarin应用程序中,我习惯于使用Forms9Patch https://www.nuget.org/packages/Forms9Patch,但这与MAUI不兼容。

ie3xauqp

ie3xauqp1#

在有人编写文本自动调整器之前,请考虑在代码中根据窗口宽度设置字体大小。

// ----- 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);

重要提示:这里假设myLabel在一个自动调整窗口宽度大小的布局中。如果窗口是窗口宽度的一半,标签应该是窗口宽度的一半,所以文本应该是窗口宽度的一半。
注:硬编码值适用于通常在7”- 10”平板电脑上使用的应用程序;电话实现允许文本变得相当小。
如果手机是你的主要目标,相应地调整.

bf1o4zei

bf1o4zei2#

我发现这个GitHub项目的更新解决方案似乎符合我的需要。
https://github.com/carolzbnbr/OnScreenSizeMarkup希望它对每个管理相同问题的人都有用!编码愉快

相关问题