java 单个 TextView 中的多个字体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10675070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple TypeFace in single TextView
提问by JustMe
I want to set the first character on TextView
with a TypeFace
and the second character with a different Type face and so on.
I read this example:
我想TextView
用 a设置第一个字符,用TypeFace
不同的 Type face 设置第二个字符,依此类推。
我读了这个例子:
Spannable str = (Spannable) textView.getText();
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7
,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
but it didn't help me, because I want to set multiple TypeFace (external TTFs)
Any idea??
但这对我没有帮助,因为我想设置多个TypeFace (external TTFs)
任何想法?
回答by Imran Rana
Use the following code:(I'm using Bangla and Tamil font)
使用以下代码:(我使用的是孟加拉语和泰米尔语字体)
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);
The outcome is:
结果是:
This uses the CustomTypefaceSpan
class, taken from How can I use TypefaceSpan or StyleSpan with a custom Typeface?:
这使用了CustomTypefaceSpan
类,取自如何将 TypefaceSpan 或 StyleSpan 与自定义字体一起使用?:
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);
}
}