如何使用TypefaceSpan或StyleSpan用自定义的字样?自定义、如何使用、字样、StyleSpan

2023-09-12 00:07:24 作者:万众金牌女神 i

我还没有找到一个办法做到这一点。这可能吗?

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

推荐答案

嗯,我无法弄清楚如何与现有的类做到这一点,所以我延长了TypefaceSpan我自己的,现在它为我工作。这是我做的:

Well i couldn't figure out how to do it with the available classes so i extended the TypefaceSpan on my own an now it works for me. Here is what i did:

    package de.myproject.text.style;

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

我希望它能帮助,如果有人有类似的问题。

i hope it helps if someone has a similar problem.