我正在尝试在我的Xamarin表单应用程序中实现自定义字体。字体是Google的Quicksand-Regular。
清单: 字体已添加到Fonts /,根目录和Resources文件夹的不同位置。 构建操作设置为BundleResource,并且输出控制器已使用“始终复制”和“不复制”进行测试。 Plist已经修改了 UIAppFonts Quicksand-Regular.tff
字体的可用名称只是Quicksand,但我尝试使用Quicksand和Quicksand-Regular在应用程序中引用它。 我试过添加, 样式TargetType ="标签" Setter Property =" FontFamily"值="流沙" 式
到应用程序范围的资源字典,以及直接引用标签上的字体,只是指定FontFamily并将其称为特定于平台。 我看到的奇怪之处在于它在预览窗口中工作正常,标签和按钮文本正在被正确替换,但这并不适用于运行时。
我相信资源实际上并没有被正确地找到或复制到iOS项目中,但任何建议都会受到赞赏。
答案 0 :(得分:0)
我只能列出我在iOS上使用字体所做的工作:
字体是MaterialIcons-regular.ttf
已添加到资源文件夹
Build Action = BundleResources
复制到输出目录=不复制
Label FontFamily =" Material Icons" (注意空格)
将字体添加到info.plist
<key>UIAppFonts</key>
<array>
<string>MaterialIcons-Regular.ttf</string>
</array>
Here is a blog post列出了iOS上所需的步骤。它说Copy to output目录应该是Always copy。不是我发现的,而是另一个可能的绊脚石。
答案 1 :(得分:0)
要使用自定义字体,您需要执行以下操作:
**共享代码**
创建一个新的类,派生自想要使用自定义字体显示的元素,例如标签:
CustomFontLabel.cs
public class CustomFontLabel : Label
{
}
是的,它基本上是一个空类。
Android 将字体(ttf文件)添加到应用程序的资产(不是资源!),并将构建操作设置为“ AndroidAsset”。
现在在您的android项目中创建一个自定义渲染器:
CustomFontRenderer.cs
[assembly: ExportRenderer(typeof(CustomFontLabel), typeof(CustomFontRenderer))]
namespace MyNamespace.Droid.Renderer.Elements
{
public class CustomFontRenderer: LabelRenderer
{
public CustomFontRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
TextView label = (TextView)Control;
if (e.NewElement?.FontFamily != null)
{
Typeface font = null;
// the try-catch block will ensure the element is at least rendered with default
// system font in Xamarin Previewer instead of crashing the view
try
{
font = Typeface.CreateFromAsset(AndroidApp.Application.Context.Assets, e.NewElement.FontFamily);
}
catch (Exception)
{
font = Typeface.Default;
}
label.Typeface = font;
}
}
}
iOS
将字体添加到资源文件夹,并确保将构建操作设置为“ BundleResource”。
接下来,将字体添加到info.plist中,例如:
<key>UIAppFonts</key>
<array>
<string>fontawesome.ttf</string>
<string>OpenSans-Light.ttf</string>
<string>OpenSans-Bold.ttf</string>
<string>OpenSans-LightItalic.ttf</string>
<string>OpenSans-Italic.ttf</string>
<string>OpenSans-Regular.ttf</string>
<string>Lato-Bold.ttf</string>
<string>Lato-Regular.ttf</string>
</array>
现在添加一个自定义渲染器:
CustomFontRenderer.cs
[assembly: ExportRenderer(typeof(CustomFontLabel), typeof(CustomFontRenderer))]
namespace MyNamespace.iOS.Renderer.Elements
{
public class CustomFontRenderer : LabelRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
{
base.OnElementChanged(e);
if (e.NewElement != null && e.NewElement.FontFamily != null)
{
e.NewElement.FontFamily = e.NewElement.FontFamily.Replace(".ttf", "");
}
}
}
}
现在回到表单视图,您可以插入自定义标签:
<elements:CustomFontLabel Text="A simple label using font family 'Lato'" FontFamily="Lato-Bold.ttf" />