giani.sim
giani.sim

Reputation: 277

Xamarin Android TypefaceSpan with custom font in Assets folder

As the title states, I need to use a TypefaceSpan object with a custom font present inside the Assets but I can't find the correct way to achieve this. The file of the font is "HelveticaNeueLTCom-BdCn.ttf"

These are my two attempt which did not work for me:

// 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;

Anyone has some hints or advice?

Upvotes: 2

Views: 644

Answers (1)

Eli
Eli

Reputation: 444

Almost one year later but I faced the same problem and I found this way of achieving it.

I saw you posted the same question in the Xamarin forum here but the link you wrote in your answer is broken. However, I think that it is this post that helped you as it helped me. So here the way to go.

First create a custom TypefaceSpan like this

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);
    }
  }
}

Then use this CustomTypefaceSpan to add a span to the SpannableString

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;

Upvotes: 3

Related Questions