Xamarin Android TypefaceSpan在Assets文件夹中使用自定义字体

时间:2016-11-28 16:47:40

标签: xamarin.android custom-font android-typeface

正如标题所述,我需要使用TyperesSpan对象,其中包含Assets中存在的自定义字体,但我找不到实现此目的的正确方法。 该字体的文件是“HelveticaNeueLTCom-BdCn.ttf”

这是我的两次尝试,对我不起作用:

// first attempt
var textViewTitle = new TextView(Context);
var span = new SpannableString("MyLongTitle");
span.SetSpan(new TypefaceSpan("HelveticaNeueLTCom-BdCn.ttf"), 0, 5, SpanTypes.ExclusiveExclusive);
textViewTitle.TextFormatted = span;


// second attempt
var textViewTitle = new TextView(Context);
var span = new SpannableString("MyLongTitle");
span.SetSpan(new Typeface(Typeface.CreateFromAsset(Context.Assets, "fonts/HelveticaNeueLTCom-BdCn.ttf")), 0, 5, SpanTypes.ExclusiveExclusive);
textViewTitle.TextFormatted = span;

任何人都有一些提示或建议吗?

1 个答案:

答案 0 :(得分:1)

差不多一年后,我遇到了同样的问题,我找到了实现这一目标的方法。

我看到你在Xamarin论坛here发布了同样的问题,但你在答案中写的链接已经破了。但是,我认为this post帮助了我,因为它帮助了我。 所以这里要走的路。

首先像这样创建一个自定义TypefaceSpan

using System;
using Android.OS;
using Android.Runtime;
using Android.Text.Style;
using Android.Graphics;
using Android.Text;

namespace Droid.Spans
{
  public class CustomTypefaceSpan : TypefaceSpan
  {
    private readonly Typeface _typeface;

    public CustomTypefaceSpan(Typeface typeface)
     : base(string.Empty)
    {
      _typeface = typeface;
    }
    public CustomTypefaceSpan(IntPtr javaReference, JniHandleOwnership transfer)
      : base(javaReference, transfer)
    {
    }
    public CustomTypefaceSpan(Parcel src)
     : base(src)
    {
    }
    public CustomTypefaceSpan(string family)
     : base(family)
    {
    }
    public override void UpdateDrawState(TextPaint ds)
    {
      ApplyTypeface(ds, _typeface);
    }
    public override void UpdateMeasureState(TextPaint paint)
    {
      ApplyTypeface(paint, _typeface);
    }
    private static void ApplyTypeface(Paint paint, Typeface tf)
    {
      paint.SetTypeface(tf);
    }
  }
}

然后使用此CustomTypefaceSpanSpannableString

添加范围
var spannableString = new SpannableString("Anything to write with a special font");
spannableString.SetSpan(new CustomTypefaceSpan(Typeface.CreateFromAsset(Assets, "HelveticaNeueLTCom-BdCn.ttf"), 0, 7, SpanTypes.InclusiveInclusive);
textView.TextFormatted = spannableString;