gpt4 book ai didi

java - 单个 TextView 中的多个 TypeFace

转载 作者:IT老高 更新时间:2023-10-28 20:48:52 26 4
gpt4 key购买 nike

我想将 TextView 上的第一个字符设置为 TypeFace,将第二个字符设置为不同的 Type face,依此类推。
我读了这个例子:

Spannable str = (Spannable) textView.getText();
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7
,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

但这对我没有帮助,因为我想设置多个 TypeFace (external TTFs)
有什么想法吗??

最佳答案

使用以下代码:(我使用的是孟加拉语和泰米尔语字体)

  TextView txt = (TextView) findViewById(R.id.custom_fonts);  
txt.setTextSize(30);
Typeface font = Typeface.createFromAsset(getAssets(), "Akshar.ttf");
Typeface font2 = Typeface.createFromAsset(getAssets(), "bangla.ttf");
SpannableStringBuilder SS = new SpannableStringBuilder("আমারநல்வரவு");
SS.setSpan (new CustomTypefaceSpan("", font2), 0, 4,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
SS.setSpan (new CustomTypefaceSpan("", font), 4, 11,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
txt.setText(SS);

结果是:

enter image description here


这使用 CustomTypefaceSpan 类,取自 How can I use TypefaceSpan or StyleSpan with a custom Typeface? :


package my.app;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;

public class CustomTypefaceSpan extends TypefaceSpan {

private final Typeface newType;

public CustomTypefaceSpan(String family, Typeface type) {
super(family);
newType = type;
}

@Override
public void updateDrawState(TextPaint ds) {
applyCustomTypeFace(ds, newType);
}

@Override
public void updateMeasureState(TextPaint paint) {
applyCustomTypeFace(paint, newType);
}

private static void applyCustomTypeFace(Paint paint, Typeface tf) {
int oldStyle;
Typeface old = paint.getTypeface();
if (old == null) {
oldStyle = 0;
} else {
oldStyle = old.getStyle();
}

int fake = oldStyle & ~tf.getStyle();
if ((fake & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}

if ((fake & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}

paint.setTypeface(tf);
}
}

关于java - 单个 TextView 中的多个 TypeFace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10675070/

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