【问题标题】:Xamarin.Forms: custom font and FontAttributesXamarin.Forms:自定义字体和 FontAttributes
【发布时间】:2019-01-13 12:15:46
【问题描述】:

我在一个 Xamarin.Forms 项目上工作,我在其中添加了 2 个 Google 字体:Montserrat 和 RobotoCondensed。

我可以在 iOS 和 Android 上使用标签或按钮在我的应用中毫无问题地使用这些字体。

但是,当我尝试应用 Italic 或 Bold 之类的 FontAttributes 时,这不起作用。

我首先只添加了“主”字体(“Montserrat-Regular”和“RobotoCondensed-Regular”)。然后我添加了“辅助”字体(“Italic”、“Bold”、“BoldItalic”),但这并没有改变任何东西。

是不是我做错了什么?

【问题讨论】:

    标签: android ios fonts xamarin.forms attributes


    【解决方案1】:
    • 您还需要包含RobotoCondensed-Bold 字体才能应用粗体效果,只有RobotoCondensed 字体您无法应用该效果。
    • 对于自定义字体,您需要添加这些字体才能达到效果。
    • 无论您想在哪里应用bold 或Italic 字体,都可以使用RobotoCondensed-Bold 或RobotoCondensed-Italic 等字体。

    您可以参考此链接:https://xamarinhelp.com/custom-fonts-xamarin-forms/

    希望这可以解决您的问题。

    【讨论】:

      【解决方案2】:

      正如in this blog post 和提到的in the docs 所述,您需要添加所需的所有字体样式。例如RobotoCondensed-bold、RobotoCondensed-regular 和 RobotoCondensed-italic。

      然后您可以以特定于平台的方式引用它们。在 android 上,您放在Assets/Fonts 中的字体由字符串Fonts/RobotoCondensed-bold.ttf#RobotoCondensed-bold 引用,其中第一部分由文件名确定,# 之后的部分是PostscriptName of the font。 在 iOS 上,您只需要字体名称。

      FontFamily = Device.RuntimePlatform == Device.iOS ? "Lobster-Regular" : null // set only for iOS

      FontFamily = Device.RuntimePlatform == Device.Android ? "Lobster-Regular.ttf#Lobster-Regular" : null // set only for Android

      为了更容易引用字体,您可以在App.xaml 中定义特定于平台的样式:

      <OnPlatform x:TypeArguments="x:String" x:Key="MyFontRegular">
         <On Platform="Android" Value="Fonts/myfont-regular.ttf#MyFont-Regular" />
         <On Platform="iOS" Value="MyFont-Regular" />
      </OnPlatform>
      

      设置FontFamily="{StaticResource MyFontRegular}" 以应用此字体。这有效地停用了FontAttributes 在同一元素上设置的效果。

      如果您的字体样式只是常见的regular、bold 和italic,您可以通过设置FontFamily="My FontFamily Name" 使用FontAttributes 引用它们,其中字体系列名称可以像找到字体的 PostscriptName 一样找到。不过,我只是偶然发现了使用FontAttributes 的选项。我不知道这是否是记录在案的行为。它似乎不适用于dashed 或medium 等其他样式。还值得指出的是,设置 FontFamily 和 FontAttributes 的结果与指定包含样式的确切字体看起来并不完全相同。有可能,使用 FontAttributes 会使 Xamarin 忽略 FontFamily。

      【讨论】:

      • 从 Xamarin.Forms 4.5.530 及更高版本开始,无需指定平台,也无需将字体文件添加到每个本机项目。这是一个很棒的指南 devblogs.microsoft.com/xamarin/embedded-fonts-xamarin-forms
      猜你喜欢
      • 2018-01-21
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 2016-04-08
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多