问题
In a xamarin.forms app, how could I customize named font sizes depending on the screen-size for the default ones don't work for me?
mainScale.LabelFontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)) * 2.5;
I've hardcoded 2.5 because it looks better.
Could you please let me know how I could have these hardcoded ones changed to a dynamic factor in a cross-platform app?
回答1:
This is a Idea to how to create sizes.
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}"/>
回答2:
I have come across a cross-platform screen resolution solution given by Allan Ritchie GitHub link and the nuget package is Nuget link
In the shared .net standard library, in the respective ContentView, the below code works:
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
}
来源:https://stackoverflow.com/questions/48401255/customize-named-font-sizes-depending-on-the-screen-size