首页 > 解决方案 > Xamarin 中的自适应字体帮助

问题描述

所以目前我有一个在我的设备上看起来很棒的应用程序,我看到的但在另一台设备上看起来像这样。两种设备都是 android,我使用了预设的 FontSize(微、小、默认、大)。

我已经使用了这个的变体,但我无法让它正常工作,结果是这样的。我实际上发现,如果我将结果除以 2,它实际上会给出一个不错的结果,但我想确保我没有做任何根本错误的事情,或者是否有更简单的方法!

这是我的 xaml 标签,每个标签都位于网格集中的框架中,每行占给定空间的 1/5。

<Frame Grid.Row="4" Grid.Column="0" 
                   BorderColor="Gold" BackgroundColor="black" 
                   Padding="2" Margin="0">

                <Label Text="Player Search" TextColor="Gold"  FontSize="Default"
                        BackgroundColor="Transparent"   Padding="0"  Margin="0"
                        ClassId="results" x:Name="PlayerSearchLbl" 
                       HorizontalTextAlignment="Center" VerticalTextAlignment="Center"                      
                        HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                    <Label.GestureRecognizers>
                        <TapGestureRecognizer
                            Tapped="Button_Pressed"/>
                    </Label.GestureRecognizers>
                </Label>
            </Frame>

我的 GetMaxFont 函数,基本上来自教程

    public int GetMaxFontSize(Label label)
    {
        double lineHeight = Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android ? 1.2 : 1.3;

        double charWidth = 0.5;

        label.Text = String.Format(label.Text, lineHeight, charWidth, label.Width, label.Height);

        int charCount = label.Text.Length; 

        int fontSize = (int)Math.Sqrt (label.Width * label.Height / (charCount * lineHeight * charWidth));

        return fontSize;
    }

如果这里需要的话,我会循环使用最大字体大小以获得最小的字体,并将我的所有标签设置为相同的字体。

    private void SetFont()
    {
        int minFontSize = 10000;
        foreach(Label label in labelList)
        {
            int fontSize = fontSizeController.GetMaxFontSize(label);
              if (fontSize < minFontSize)
            {
                minFontSize = fontSize;
            }
        }            
        foreach(Label label in labelList)
        {
            label.FontSize = minFontSize;  
        }
    }

标签: xamarinxamarin.androidxamarin.ios

解决方案


似乎此功能正在 Xamarin 4.6 Pull 7981中为 Android 实现


推荐阅读