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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值