Search code examples
xamarinxamarin.androidxamarin.ios

Adaptive font help in Xamarin


So currently I have an app that looks great on my device, what I see but on another device It looked like this. Both devices are android and I have used the preset FontSize's (micro, small, default, large).

I have used a variation of this but I cannot get it to work corrently, It comes out like this. I actually find that if I divide the result by 2 it actually gives a decent result but I want to make sure I am not doing anything fundamentally wrong or if there is a much simpler way!

Here is my xaml label, each are in a frame in a grid set with each row 1/5th of the space given.

<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>

my GetMaxFont function, basically from the tutorial

    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;
    }

and in case is it needed here I cycle through the max font sizes to get the smallest and set all my labels to the same font.

    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;  
        }
    }

Solution

  • It seems this feature is in progresses of being implemented for Android in Xamarin 4.6 Pull 7981