要使用自定义字体,您需要执行以下操作:
** 共享代码 **
创建一个从元素派生的新类,您希望使用自定义字体显示,例如一个标签:
CustomFontLabel.cs
public class CustomFontLabel : Label
{
}
是的,它基本上是一个空类。
安卓
将字体(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" />