【问题标题】:How to change font family of label in Xamarin.Forms?如何更改 Xamarin.Forms 中标签的字体系列?
【发布时间】:2018-10-07 14:48:17
【问题描述】:

我尝试使用 CSS 和 XAML 更改标签的字体系列,但字体没有反映。我正在尝试在我的应用程序中使用蒙特塞拉特字体。我该如何解决这个问题?

XAML 代码:

<Label StyleClass="label" Text="Sample"/>

CSS 代码:

.label{
    font-family: Montserrat;
}

【问题讨论】:

标签: c# xamarin xamarin.forms xamarin.android


【解决方案1】:

为了在您的项目中使用自定义字体,您必须执行以下操作:

在您的 Android 项目中,将字体文件放在 Assets 文件夹中,并确保构建类型为 AndroidAsset。

然后您可以在您的 XAML 中,在资源字典中声明字体(例如在 App.xaml 中

<ResourceDictionary>
    <OnPlatform x:TypeArguments="x:String" x:Key="BoldFont">
        <On Platform="Android" Value="OpenSans-Bold.ttf#Open Sans" />
        <On Platform="UWP" Value="/Assets/OpenSans-Bold.ttf#Open Sans" />
        <On Platform="iOS" Value="OpenSans-Bold" />
    </OnPlatform>
    <OnPlatform x:TypeArguments="x:String" x:Key="NormalFont">
        <On Platform="Android" Value="OpenSans-Regular.ttf#Open Sans" />
        <On Platform="UWP" Value="/Assets/OpenSans-Regular.ttf#Open Sans" />
        <On Platform="iOS" Value="OpenSans-Regular" />
    </OnPlatform>
</ResourceDictionary>

要使用自定义字体,您可以:

<StackLayout>
    <Label Text="Welcome to Xamarin Forms! (OpenSans-Bold)" FontFamily="{StaticResource BoldFont}" />
    <Label Text="Welcome to Xamarin Forms! (OpenSans-Regular)" FontFamily="{StaticResource NormalFont}" />
    <Label Text="Welcome to Xamarin Forms! (Default)" />
</StackLayout>

【讨论】:

  • 感谢您仅回答一个问题。当我将字体添加到 Asset 文件夹时,我现在可以在我的 css 文件中使用该字体吗?
【解决方案2】:

v4.5.530+ 中,您可以轻松添加自定义嵌入字体,而不必担心跨平台问题:

  • 在您的共享项目中添加您的自定义字体文件(*.tff*.otf)。

  • 右键单击字体文件 > 属性 > 在 Build Action 中选择 Embedded Resource

  • 在共享项目的某处添加ExportFont 属性(通常在App.xaml.csAssemblyInfo.cs 中)。
// "Font Awesome 5 Pro-Regular-400.otf" is the font file name witout the subfolders path
// Alias is the name to reference in code
[assembly: ExportFont("Font Awesome 5 Pro-Regular-400.otf", Alias = "FARegular")]

namespace YourProject.Shared
{
    public partial class App : Application
    {

        public App()
        {
            InitializeComponent();
            // ...
        }
    }
}
  • 更新控件中的自定义字体系列:
<Label FontFamily="FARegular" Text="&#xf002;" />

参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2019-09-10
    相关资源
    最近更新 更多