【自定義TextView】一個Text,兩段文字,兩種顏色,兩種大小,文字底部平行

最近做個項目,有個UI如圖

github:https://github.com/ai2101039/YLDiscolorTextView

UI圖

可能小夥伴第一時間想到,弄兩個 textView,不過最近我癡迷onDraw,所以考慮自定義一個TextView,以達到最後的效果。

結果圖

(綠色爲baseLine)

也許有的小夥伴問,你這數字和漢字也沒有底部對齊啊。

文字是以baseLine作爲繪製基線,其Ascent、BaseLine、Descent 只與字號(如 14sp,16sp)和 文字字體(如 “微軟雅黑”,“宋體”)相關。

這是小編用PS 做的。

代碼

使用字號大的那段文字的baseline

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        TextPaint textPaint = beforeSize < afterSize ? afterPaint : beforePaint;
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        float y = -fontMetrics.ascent;
        canvas.drawText(beforeText, 0, y, beforePaint);
        canvas.drawText(afterText, beforeWidth, y, afterPaint);

        //  baseLine
        Paint paint = new Paint();
        paint.setColor(resources.getColor(R.color._238E23));
        paint.setStrokeWidth(1);
        paint.setAntiAlias(true);
        canvas.drawLine(0, y, beforeWidth + afterWidth, y, paint);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章