簡體   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