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

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

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

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 15:39

    Whilst notme has essentially the right idea, the solution given is a bit hacky as "family" becomes redundant. It is also slightly incorrect because TypefaceSpan is one of the special spans that Android knows about and expects certain behaviour with respect to the ParcelableSpan interface (which notme's subclass does not properly, nor is it possible to, implement).

    A simpler and more accurate solution would be:

    public class CustomTypefaceSpan extends MetricAffectingSpan
    {
        private final Typeface typeface;
    
        public CustomTypefaceSpan(final Typeface typeface)
        {
            this.typeface = typeface;
        }
    
        @Override
        public void updateDrawState(final TextPaint drawState)
        {
            apply(drawState);
        }
    
        @Override
        public void updateMeasureState(final TextPaint paint)
        {
            apply(paint);
        }
    
        private void apply(final Paint paint)
        {
            final Typeface oldTypeface = paint.getTypeface();
            final int oldStyle = oldTypeface != null ? oldTypeface.getStyle() : 0;
            final int fakeStyle = oldStyle & ~typeface.getStyle();
    
            if ((fakeStyle & Typeface.BOLD) != 0)
            {
                paint.setFakeBoldText(true);
            }
    
            if ((fakeStyle & Typeface.ITALIC) != 0)
            {
                paint.setTextSkewX(-0.25f);
            }
    
            paint.setTypeface(typeface);
        }
    }
    

提交回复
热议问题