Xamarin Android在同一textview中使用多种字体

时间:2018-06-09 15:15:58

标签: c# android xamarin fonts xamarin.android

我使用Xamarin作为Android应用,我创建了一个自定义TypeFace,如下所示:

Typeface weatherFont = Typeface.CreateFromAsset(Assets, "Weather.ttf");

我的问题是我必须将string分配给TextView,我需要将前3个字符的字体设置为默认的android字体,剩下的字体设置为weatherFont {1}}字体。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

在API-27之前,您需要一个自定义CharacterStyle子类才能将自定义Typeface应用于Spannable

实施例

var sushiFont = Typeface.CreateFromAsset(Assets, "Tastysushi.ttf");
var spannable = new SpannableString("123 = SushiHangover");
spannable.SetSpan (new CustomTypefaceSpan(sushiFont), 3, spannable.Length(), SpanTypes.ExclusiveInclusive);
button.SetText(spannable, TextView.BufferType.Spannable);

或者在API-21(+)中,您可以使用SetSpan来避免SpannableStringBuilder.Append char开始/结束索引:

var sushiFont = Typeface.CreateFromAsset(Assets, "Tastysushi.ttf");
var spannableString = new SpannableStringBuilder("123");
var spannable = new SpannableString(" = SushiHangover");
spannableString.Append(spannable, new CustomTypefaceSpan(sushiFont), SpanTypes.ExclusiveInclusive);
button.SetText(spannableString, TextView.BufferType.Spannable);

在API-28 +中,您可以直接创建直接包含不同Typeface的跨度,而无需使用CharacterStyle子类:

spannableString.Append(spannable, new TypefaceSpan(sushiFont), SpanTypes.ExclusiveInclusive);

CustomTypefaceSpan类

public class CustomTypefaceSpan : MetricAffectingSpan
{
    readonly Typeface typeFace;

    public CustomTypefaceSpan(Typeface typeFace)
    {
        this.typeFace = typeFace;
    }

    public override void UpdateDrawState(TextPaint tp)
    {
        tp.SetTypeface(typeFace);
    }

    public override void UpdateMeasureState(TextPaint p)
    {
        p.SetTypeface(typeFace);
    }
}