【发布时间】:2020-01-24 16:34:04
【问题描述】:
- Designer 在使用 Assets 文件夹中的 ttf 文件时崩溃。
- 在我的代码中,我使用 ttf 文件来设置 TextView 字体属性(如 Typeface = Typeface.CreateFromAsset(this.Context.Assets, "fonts/Sample_Icons.ttf"),
- 它使我的设计器页面崩溃。
请给我建议。
【问题讨论】:
标签: xamarin.android
请给我建议。
【问题讨论】:
标签: xamarin.android
将ttf文件放入Assets文件夹后,可以通过以下方法访问ttf文件:
AssetManager assets = this.Assets;
Typeface font = Typeface.CreateFromAsset(assets, "Lobster-Regular.ttf");
// and use like this
Button button = (Button)FindViewById(Resource.Id.btn);
button.SetTypeface(font, TypefaceStyle.Normal);
也就是说,你只需要去掉ttf文件前的fonts,你可以这样使用:
Typeface.CreateFromAsset(this.Assets, "Sample_Icons.ttf");
而不是:
Typeface.CreateFromAsset(this.Context.Assets, "fonts/Sample_Icons.ttf");
有一个简单的demo,可以查看here。效果如下:
【讨论】:
我使用了基于这篇文章的解决方案:
https://blog.mzikmund.com/2017/07/checking-for-design-mode-in-xamarin-forms/
public static class EmulatorHelper
{
// https://blog.mzikmund.com/2017/07/checking-for-design-mode-in-xamarin-forms/
public static bool IsDesigner { get; set; }
#if !RELEASE
= true;
#endif
}
然后在应用程序的某个地方启动,例如 AndroidApp.cs
public class AndroidApp : App
{
public override void Initialize()
{
base.Initialize();
EmulatorHelper.IsDesigner = false;
}
}
最后替换
Typeface font = Typeface.CreateFromAsset(assets, "Lobster-Regular.ttf");
与
Typeface font = !EmulatorHelper.IsDesigner
? Typeface.CreateFromAsset(assets, "Lobster-Regular.ttf")
: Typeface.Default;
此解决方案的缺点是您会在设计器中看到默认字体,但它比带有错误标签的橙色框要好得多:)
【讨论】: