How can I use TypefaceSpan or StyleSpan with a custom Typeface?

后端 未结 5 2012
北恋
北恋 2020-11-22 14:59

I have not found a way to do this. Is it possible?

5条回答
  •  一向
    一向 (楼主)
    2020-11-22 15:55

    Spannable typeface: In order to set a different font typeface to some portion of text, a custom TypefaceSpan can be used, as shown in the following example:

    spannable.setSpan( new CustomTypefaceSpan("SFUIText-Bold.otf",fontBold), 0,
    firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan( new CustomTypefaceSpan("SFUIText-Regular.otf",fontRegular),
    firstWord.length(), firstWord.length() + lastWord.length(),
    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    text.setText( spannable );
    

    However, in order to make the above code working, the class CustomTypefaceSpan has to be derived from the class TypefaceSpan. This can be done as follows:

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

提交回复
热议问题