根据屏幕大小自定义命名字体大小

时间:2018-01-23 12:02:04

标签: xamarin xamarin.forms

在xamarin.forms应用中,我如何根据屏幕尺寸自定义指定的字体大小,默认值不适合我?

mainScale.LabelFontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)) * 2.5;

我已经硬编码2.5,因为它看起来更好。

请您告诉我如何将这些硬编码的内容更改为跨平台应用中的动态因素?

2 个答案:

答案 0 :(得分:3)

这是如何创建尺寸的想法。

App.xaml.cs

public static double DisplayScreenWidth = 0f;
public static double DisplayScreenHeight = 0f;

public static double Size1 { get; private set; }
public static double Size2 { get; private set; }
public static double Size3 { get; private set; }

if(DisplayScreenHeight > 560)
{
     Size1 = Device.GetNamedSize(NamedSize.Large, typeof(Label)) * 1.6;
}
else
{
     Size1 = Device.GetNamedSize(NamedSize.Large, typeof(Label)) * 1.2;
}

Activity.cs

App.DisplayScreenWidth = (double)Resources.DisplayMetrics.WidthPixels / (double)Resources.DisplayMetrics.Density;
App.DisplayScreenHeight = (double)Resources.DisplayMetrics.HeightPixels / (double)Resources.DisplayMetrics.Density;

的App.xaml

xmlns:local="clr-namespace:Mobile" >

<Style x:Key="baseStyle" TargetType="Label">
            <Style.Triggers>
                <Trigger  TargetType="Label"
                       Property="FontAttributes" 
                       Value="None">
                    <Setter Property="FontFamily" Value="OpenSans-Regular.ttf#Regular" />
                </Trigger>
                <Trigger  TargetType="Label"
                       Property="FontAttributes" 
                       Value="Bold">
                    <Setter Property="FontFamily" Value="OpenSans-Bold.ttf#Regular-Bold" />
                </Trigger>
            </Style.Triggers>
        </Style>

        <!-- TAMANHO DE FONTES -->
        <Style x:Key="Size1" TargetType="Label" BasedOn="{StaticResource baseStyle}">
            <Setter Property="FontSize" Value="{Binding Source={x:Static local:App.Size1}}"/>
        </Style>
        <Style x:Key="Size2" TargetType="Label" BasedOn="{StaticResource baseStyle}">
            <Setter Property="FontSize" Value="{Binding Source={x:Static local:App.Size2}}"/> 
        </Style>

Home.xaml

<label Text="Hello from Xamarin Forms" Style="{StaticResource Size1}"/>

答案 1 :(得分:0)

我遇到过Allan Ritchie GitHub link给出的跨平台屏幕分辨率解决方案,而nuget包是Nuget link

在共享的.net标准库中,在相应的ContentView中,以下代码有效:

    protected override void OnSizeAllocated(double width, double height)
    {
        // specific font adjustment code goes here
        if (CrossDevice.Hardware.ScreenHeight > 600)
        {
        ...              
        }
        ...

        base.OnSizeAllocated(width, height); //must be called
    }