我使用Xamarin作为Android应用,我创建了一个自定义TypeFace
,如下所示:
Typeface weatherFont = Typeface.CreateFromAsset(Assets, "Weather.ttf");
我的问题是我必须将string
分配给TextView
,我需要将前3个字符的字体设置为默认的android字体,剩下的字体设置为weatherFont
{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);
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);
}
}