繁体   English   中英

Xamarin形式:UWP和Windows 8.1中的自定义字体

[英]Xamarin forms: Custom Fonts in UWP and Windows 8.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
    )
}

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

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

注意:如果您使用的是NavigationPage,则存在一个自定义字体无法使用的错误

在Windows 8.1 / UWP上,不需要自定义渲染器来定制字体。 Xamarin示例代码仅存在两个错误:

  • 改用正斜杠('/')
  • 路径应为[font file]#[font name] (无字体样式,例如'regular')

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

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

您也可以在Xaml中使用它

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

确保BuildAction:Content将字体文件包含在项目中,并且该字体文件应该工作。

您可以尝试在Windows平台上创建一个重写Xamarin.Forms.LabelCustomRenderer ,如下所示:

[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;
            }
        }     
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM