Android——SpannableString上标,下标垂直对齐

在上一节Android——SpannableString实现顶部对齐(上标,下标)中我们已经了解,SuperscriptSpanSubscriptSpan可以实现上标和下标效果,但是不可以改变大小,且显示位置固定。
今天我们要实现的效果如下:
在这里插入图片描述
TwoScriptTextSpan .java

public class TwoScriptTextSpan extends ReplacementSpan {
    private int fontSize = -1;
    private boolean isSp;
    private int position;

    public @interface ScriptPosition {
        int LEFT_TOP = 1;
        int LEFT_BOTTOM = 2;
        int RIGHT_TOP = 3;
        int RIGHT_BOTTOM = 4;
    }

    public TwoScriptTextSpan(int fontSize, boolean isSp) {
        this.fontSize = fontSize;
        this.isSp = isSp;
    }

    public TwoScriptTextSpan(int fontSize, boolean isSp, int position) {
        this.fontSize = fontSize;
        this.isSp = isSp;
        this.position = position;
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        Paint newPaint = getCustomTextPaint(paint);
        return (int) newPaint.measureText(text, start, end);
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int
            bottom, @NonNull Paint paint) {
        Paint newPaint = getCustomTextPaint(paint);
        text = text.subSequence(start, end);
        String[] parts = text.toString().split(",");

        float width1 = newPaint.measureText(parts[0]);
        float width2 = newPaint.measureText(parts[1]);
        float maxWidth = Math.max(width1, width2);
        float minWidth = Math.min(width1, width2);

        canvas.drawText(parts[0], x + minWidth + (maxWidth - width1), y - (bottom - top) / 3f, newPaint);
        canvas.drawText(parts[1], x + minWidth + (maxWidth - width2), y, newPaint);
    }

    private TextPaint getCustomTextPaint(Paint srcPaint) {
        TextPaint textPaint = new TextPaint(srcPaint);
        if (fontSize != -1) {
            textPaint.setTextSize(isSp ? fontSize * textPaint.density : fontSize);
        }
        return textPaint;
    }
}

MainActivity.java

String format = "9,4Be -> 2000,127Jo";

SpannableString ss = new SpannableString(format);

TwoScriptTextSpan leftTopSpan = new TwoScriptTextSpan(25, true,1);
ss.setSpan(leftTopSpan, 0, 3, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
TwoScriptTextSpan rightTopSpan = new TwoScriptTextSpan(25, true,2);
ss.setSpan(rightTopSpan, 9, 17, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);

tvImageSpan.setText(ss);

你可能感兴趣的:(Android)