【问题标题】:Use different typefaces for the same TextView with HTL formatting对具有 HTL 格式的同一个 TextView 使用不同的字体
【发布时间】:2012-06-04 21:06:36
【问题描述】:

我已经知道如何为我的 TextView 指定自定义字体。截至目前,我的应用程序正在使用一种自定义字体,该字体分为两个 ttf 文件。一个用于常规字符,一个用于粗体字符。

现在,我希望能够像使用 Html.fromHtml() 一样使用两个 TextView。由于它适用于系统字体,它应该能够使用我自己的字体来完成。目前,粗体字符是用常规字体和假粗体文本绘制的,非常难看。

有什么想法吗?

谢谢

【问题讨论】:

    标签: android html typeface


    【解决方案1】:

    如果你想在单个 TextView 中使用多种自定义字体:

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

      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);
    

    结果是:


    CustomTypefaceSpan 类:

    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);
    }
    }
    

    Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多