gpt4 book ai didi

c# - Xamarin Android 同一 TextView 中的多种字体

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:07 25 4
gpt4 key购买 nike

我正在为 Android 应用程序使用 Xamarin,并且我创建了一个自定义 TypeFace,如下所示:

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

我的问题是我有一个必须分配给 TextViewstring 并且我需要将前 3 个字符的字体设置为默认的 android 字体剩下的是我的 weatherFont 字体。我该怎么做?

最佳答案

直到 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(+) 中,您可以使用 SpannableStringBuilder.Append 避免 SetSpan 字符开始/结束索引:

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 的 span,而无需使用 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);
}
}

关于c# - Xamarin Android 同一 TextView 中的多种字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com