Visual Studio 中的 FontFamily 导入不适用于 C# Xamarin

FontFamily import does not work with C# Xamarin in Visual Studio

我正在尝试导入“Lobster-Regular.ttf”https://fonts.google.com/specimen/Lobster 字体并在我的应用程序中使用它,但它 work/doesn 没有出现在我的 android模拟器。

我遵循 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/fonts 中指定的准则。见下文:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="WeatherApp.MainPage"
             BackgroundImageSource="https://wallpapercave.com/wp/wp5863622.jpg">

    <StackLayout Padding="20,20,20,20">
        <Label Text="Weatherized" FontAttributes="Bold" FontSize="30" HorizontalOptions="Center" VerticalOptions="Center"
               TextColor="White" FontFamily="Lobster"/>
    </StackLayout>

</ContentPage>

我还在汇编文件中使用了以下内容:

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
[assembly: ExportFont("Lobster-Regular.ttf", Alias = "Lobster")]

我已经下载了字体文件并将其放入我的项目解决方案中名为“Resources”的文件夹中。

知道如何解决这个问题吗?

您可以尝试的第一件事是不使用破折号 (-) 来指示间距,您可以尝试使用“ ”。下面的代码就是一个例子:

[assembly: ExportFont("Lobster Regular.ttf", Alias = "Lobster")] // notice the space

如果这不起作用 - 尝试删除名称中的所有空格,因为这可能会导致一些问题。将其重命名为 LobsterRegular.ttf.

你可以做的第二件事是尝试将字体设置为嵌入资源如果你还没有(很多人忘记了这一步)- 我和你有同样的问题 - 我将 .ttf 文件的构建操作设置为 'embedded resource' 并且它有效。

如果这不起作用 - 尝试将您的 Xamarin.Forms 版本更新到 最新的稳定版本。

如果您已经尝试了所有方法但没有任何效果 - 最后一个选项是使用可以设置字体系列的自定义渲染器:

[assembly: ExportRenderer(typeof(Xamarin.Forms.Button), typeof(CustomButtonRenderer))]
namespace Custombutton.Droid
{
    class CustomButtonRenderer : ButtonRenderer
    {
        public CustomButtonRenderer(Context context) : base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                Typeface tf = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "Lobster-Regular.ttf");
                Control.SetTypeface(tf, TypefaceStyle.Bold);
            }
        }
    }
}

如果您想走这条路 - 请记住将 .ttf 文件放在您的 Android 应用程序中。