SpannableString设置不同大小字体顶部对齐

SpannableString设置不同大小字体顶部对齐

  • 网上复制粘贴就行了
  • 设置让前两个字符串顶部对齐

网上复制粘贴就行了

private float sp2px(Context context, float sp) {
        float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
        return sp * scaledDensity;
    }

    private void setCocoBalance(String balance) {
        SpannableString spannableString = new SpannableString("余额 " + balance);
        //设置颜色
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 2, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置字体大小,true表示前面的字体大小20单位为dip
        spannableString.setSpan(new AbsoluteSizeSpan(12, true), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new AbsoluteSizeSpan(35, true), 3, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //设置字体,BOLD为粗体
        spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 3, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new TopSpan((int) sp2px(getContext(), 12), Color.parseColor("#4D4D4D")), 0, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvCocoAmount.setText(spannableString);
    }

设置让前两个字符串顶部对齐

/**
 * 使TextView中不同大小字体顶部对齐
 */
public class TopSpan extends ReplacementSpan {

    private float fontSizePx;    //px
    private int color;

    public TopSpan(float fontSizePx,int color) {
        this.fontSizePx = fontSizePx;
        this.color = color;
    }

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

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        text = text.subSequence(start, end);
        Paint p = getCustomTextPaint(paint);
        Paint.FontMetricsInt fm = p.getFontMetricsInt();
        // 此处重新计算y坐标,使字体顶部对齐
        canvas.drawText(text.toString(), x, y - ((y + fm.descent + y + fm.ascent) - (bottom + top)), p);
//        canvas.drawText(text.toString(), x, y, p);
    }

    private TextPaint getCustomTextPaint(Paint srcPaint) {
        TextPaint paint = new TextPaint(srcPaint);
        paint.setTextSize(fontSizePx);   //设定字体大小, sp转换为px
        paint.setColor(color);
        return paint;
    }
}

在这里插入图片描述

你可能感兴趣的:(Android)