1

我正在开发一个使用 font.otf 文件的应用程序。我的应用程序将在 android、ios、windows 10 和 windows 8.1 上运行。我需要为我的标签创建样式以设置字体系列。对于 android 和 ios,我引用了这个链接

我在这样的xaml页面中尝试过-

<Label.FontFamily>
        <OnPlatform x:TypeArguments="x:String">
            <OnPlatform.iOS></OnPlatform.iOS>
            <OnPlatform.Android>Lobster-Regular.ttf#Lobster-Regular</OnPlatform.Android>
            <OnPlatform.WinPhone></OnPlatform.WinPhone>
        </OnPlatform>
    </Label.FontFamily>

new Label {
    Text = "Hello, Forms!",
    FontFamily = Device.OnPlatform (
        null,
        null,
        @"\Assets\Fonts\Lobster-Regular.ttf#Lobster-Regular"
                 // Windows Phone will use this custom font
    )
}

但是当我运行我的应用程序时,字体没有为 Windows 10 和 8.1 设置。

如何为 Windows 10 和 8.1 设置字体系列。或者有没有更有效的方法来应用覆盖所有平台的字体系列?

4

2 回答 2

3

注意:如果您使用的是 NavigationPage,则会出现自定义字体不起作用的错误

在 Windows 8.1/UWP 上,您不需要自定义字体的自定义渲染器;Xamarin 示例代码只是有几个错误:

  • 改用正斜杠 ('/')
  • 路径的形式应该是[font file]#[font name](没有字体样式,例如“常规”)

所以这种情况下的路径实际上应该是

"Assets/Fonts/Lobster-Regular.ttf#Lobster"

你也可以在 Xaml 中使用它

<OnPlatform.WinPhone>Assets/Fonts/Lobster-Regular.ttf#Lobster</OnPlatform.WinPhone>

确保您的字体文件包含在您的项目中,BuildAction:Content并且它应该可以工作。

于 2017-01-18T15:44:58.557 回答
1

您可以尝试创建一个CustomRenderer覆盖Xamarin.Forms.LabelWindows 平台上的 ,如下所示:

[assembly: ExportRenderer(typeof(Xamarin.Forms.Label), typeof(MyLabelRenderer))]
namespace MyApp.CustomRenderers.Controls
{
    public class MyLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                var font = new FontFamily(@"\Assets\Fonts\Lobster-Regular.ttf#Lobster-Regular");

                if (e.NewElement != null)
                {
                    switch (e.NewElement.FontAttributes)
                    {
                        case FontAttributes.None:
                            break;
                        case FontAttributes.Bold:
                            //set bold font etc
                            break;
                        case FontAttributes.Italic:
                            //set italic font etc
                            break;
                        default:
                            break;
                    }
                }
                Control.FontFamily = font;
            }
        }     
    }
于 2017-01-17T16:01:57.097 回答