最近做個項目,有個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);
}