畫(huà)BaseLine平齊的文本

最近在項(xiàng)目中遇到好幾處類似下方這樣的帶單位、左大右小的布局


1.png
2.png

看起來(lái)很平常,兩個(gè)不同size的TextView左右布局,同時(shí)它們的baseline是平齊的,有人馬上就想到了在RelativeLayout中的子View可以使用layout_alignBaseline屬性完成這個(gè)布局,這里貼下xml文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    >

    <TextView
        android:id="@+id/tv_value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:includeFontPadding="false"
        android:textColor="@color/white"
        android:textSize="16sp" />


    <TextView
        android:id="@+id/tv_unit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/tv_value"
        android:layout_toRightOf="@id/tv_value"
        android:includeFontPadding="false"
        android:textColor="@color/white"
        android:textSize="14sp" />
</RelativeLayout>

本來(lái)以為到這里就結(jié)束了,但是設(shè)計(jì)告訴我說(shuō),這個(gè)底邊并沒(méi)有平齊,那個(gè)kg的g明明下沉了,我要的效果不是這樣的……然后我就解釋了一下因?yàn)檫@個(gè)g比較特殊,你要是m就齊了,設(shè)計(jì)大哥就問(wèn)了句那我要的能實(shí)現(xiàn)不……
這里就不得不說(shuō)一下TextView的繪制了


Text的繪制

熟悉自定義view的同學(xué)應(yīng)該知道,自定義view其實(shí)就是繪制文字和圖像,這就涉及到canvas的drawText()方法了,這里有好幾個(gè)重載的方法,看看我們經(jīng)常常用的這個(gè)方法的源碼:

/**
     * Draw the text, with origin at (x,y), using the specified paint. The
     * origin is interpreted based on the Align setting in the paint.
     *
     * @param text  The text to be drawn
     * @param x     The x-coordinate of the origin of the text being drawn
     * @param y     The y-coordinate of the baseline of the text being drawn
     * @param paint The paint used for the text (e.g. color, size, style)
     */
    public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) {
        native_drawText(mNativeCanvasWrapper, text, 0, text.length(), x, y, paint.mBidiFlags,
                paint.getNativeInstance(), paint.mNativeTypeface);
    }

這四個(gè)參數(shù)除了y其他的都很好理解,text是要繪制的文本內(nèi)容,x是x軸方向的開(kāi)始繪制的值,y參數(shù)說(shuō)明里的baseline又是什么東東……
先上圖:


3.png

這張圖里有四根線,其中3就是baseline,可以看到漢字和英文字母都會(huì)超出這個(gè)線,阿拉伯?dāng)?shù)字就不會(huì)超出這個(gè)baseline。也就是說(shuō)drawtext在垂直方向是以3為基準(zhǔn)的,所以當(dāng)我們想把文本垂直居中繪制在某一個(gè)view里,y的值是不能直接設(shè)為getHeight()/2的,也就是圖中的2號(hào)線,y值應(yīng)該向下偏移到3的位置。
這里就說(shuō)下3號(hào)線距離1號(hào)線和4號(hào)線分別對(duì)應(yīng)兩個(gè)值,他們是FontMetrics這個(gè)類中的兩個(gè)值,ascent(負(fù)數(shù))和descent的絕對(duì)值。在FontMetrics有五個(gè)float類型值:

  • leading 留給文字音標(biāo)符號(hào)的距離

  • ascent 從baseline線到最高的字母頂點(diǎn)到距離,負(fù)值

  • top 從baseline線到字母最高點(diǎn)的距離加上ascent, |top|=|ascent|+|leading|

  • descent 從baseline線到字母最低點(diǎn)到距離

  • bottom 和top類似,系統(tǒng)為一些極少數(shù)符號(hào)留下的空間,top和bottom總會(huì)比ascent和descent大一點(diǎn)的就是這些少到忽略的特殊符號(hào)。

想要了解詳情的可以看看FontMetrics這個(gè)類的源碼。


所以到這里,實(shí)現(xiàn)平齊效果的思路就很明了,自定義一個(gè)view,繼承自View,畫(huà)兩個(gè)text即可實(shí)現(xiàn),關(guān)鍵在于第二個(gè)text的baseline設(shè)置成多少。
先貼上完整的類

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;


/**
 * Description:
 * Created by hdz on 2017/6/1.
 */

public class AlignmentView extends View {

    //數(shù)值的畫(huà)筆
    private Paint valuePaint;

    //單位的畫(huà)筆
    private Paint unitPaint;

    private int valueColor = Color.BLACK;

    private int unitColor = Color.BLACK;

    private float valueTextSize = 30;

    private float unitTextSize = 24;

    //數(shù)值和單位之間的padding
    private float space = 0;

    /**
     * 類型
     * 0:下方未超出baseline
     * 1:下方超出baseline
     */
    private int type;

    private String value;

    private String unit;

    //數(shù)值對(duì)應(yīng)baseline的y值
    private float valueDrawY;
    
    private Paint.FontMetrics valueMetrics;

    private Paint.FontMetrics unitMetrics;

    public AlignmentView(Context context) {
        this(context, null, 0);
    }

    public AlignmentView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AlignmentView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {

        if (attrs == null) {
            return;
        }

        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.AlignmentView, defStyleAttr, 0);
        value = array.getString(R.styleable.AlignmentView_value);
        unit = array.getString(R.styleable.AlignmentView_unit);
        space = array.getDimension(R.styleable.AlignmentView_space, 0);
        unitColor = array.getColor(R.styleable.AlignmentView_unitColor, Color.BLACK);
        valueColor = array.getColor(R.styleable.AlignmentView_valueColor, Color.BLACK);
        valueTextSize = array.getDimension(R.styleable.AlignmentView_valueSize, 30);
        unitTextSize = array.getDimension(R.styleable.AlignmentView_unitSize, 24);
        type = array.getInt(R.styleable.AlignmentView_type, 0);

        if (TextUtils.isEmpty(value)) {
            value = "數(shù)值";
        }

        if (TextUtils.isEmpty(unit)) {
            unit = "單位";
        }

        valuePaint = new Paint();
        valuePaint.setAntiAlias(true);
        valuePaint.setTextSize(valueTextSize);
        valuePaint.setColor(valueColor);
        valuePaint.setTextAlign(Paint.Align.LEFT);

        unitPaint = new Paint();
        unitPaint.setAntiAlias(true);
        unitPaint.setTextSize(unitTextSize);
        unitPaint.setColor(unitColor);
        unitPaint.setTextAlign(Paint.Align.LEFT);

        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        valueMetrics = valuePaint.getFontMetrics();
        unitMetrics = unitPaint.getFontMetrics();

        //獲取文字的寬高
        float valueH = valueMetrics.descent - valueMetrics.ascent;
        float valueW = valuePaint.measureText(value);
        float unitH = unitMetrics.descent - unitMetrics.ascent;
        float unitW = unitPaint.measureText(unit);

        int realH = (int) (Math.max(valueH, unitH) + getPaddingBottom() + getPaddingTop());
        int realW = (int) (valueW + unitW + getPaddingLeft() + getPaddingRight() + space);

        int width = measureSize(realW, widthMeasureSpec);
        int height = measureSize(realH, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    private int measureSize(int defaultSize, int measureSpec) {
        int resultSize = defaultSize;
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);

        switch (mode) {
            case MeasureSpec.AT_MOST:
            case MeasureSpec.UNSPECIFIED:
                break;
            case MeasureSpec.EXACTLY:
                resultSize = size;
                break;
        }
        return resultSize;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawValue(canvas);
        drawUnit(canvas);
        canvas.drawLine(getPaddingLeft(), valueDrawY, getWidth(), valueDrawY, unitPaint);
    }

//    畫(huà)左側(cè)的數(shù)值
    private void drawValue(Canvas canvas) {
       //y值的計(jì)算,向下偏移
        valueDrawY = getHeight() / 2 + (Math.abs(valueMetrics.ascent) - valueMetrics.descent) / 2;
        canvas.drawText(value, getPaddingLeft(), valueDrawY, valuePaint);
    }

//    畫(huà)右側(cè)的單位
    private void drawUnit(Canvas canvas) {
        float valueWidth = valuePaint.measureText(value);
        float x = getPaddingLeft() + valueWidth + space;
        float y = valueDrawY;
        if (type == 1) {
//            當(dāng)?shù)撞砍鯾aseline的時(shí)候,應(yīng)該向上偏移單位對(duì)應(yīng)的descent值
            y = valueDrawY - unitMetrics.descent;
        }
        canvas.drawText(unit, x, y, unitPaint);
    }

//    向外部提供設(shè)置值的方法
    public void setValue(String value) {
        this.value = value;
        invalidate();
    }

    public void setUnit(String unit) {
        this.unit = unit;
        invalidate();
    }
}

attrs:

<declare-styleable name="AlignmentView">
        <attr name="value" format="string"/>
        <attr name="unit" format="string"/>
        <attr name="valueColor" format="color" />
        <attr name="unitColor" format="color" />
        <attr name="valueSize" format="dimension" />
        <attr name="unitSize" format="dimension" />
        <attr name="space" format="dimension"/>

        <attr name="type">
            <enum name="NORMAL" value="0"/>
            <enum name="DESCENT_BEYOND" value="1"/>
        </attr>
    </declare-styleable>

這里需要說(shuō)下就是drawUnit方法中drawText中的y值,當(dāng)y = valueDrawY時(shí)也就達(dá)到了上面layout_alignBaseline的效果,如果還要調(diào)整,就需要
y = valueDrawY - unitMetrics.descent了,這里descent應(yīng)該是unit所對(duì)應(yīng)的。

布局文件

 <com.example.handezhao.align.AlignmentView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="#57df87"
        android:padding="10dp"
        app:space="5dp"
        app:unitColor="#00f"
        app:unitSize="20sp"
        app:valueColor="#454545"
        app:valueSize="40sp"
        app:value="1234567890"
        app:unit="abcdefghijk"
        android:layout_marginTop="20dp"
        app:type="DESCENT_BEYOND"
        />

最后看看兩種type的效果:

type0.png
type1.png

??????,這里的type可以根據(jù)不同的需求增加,比如右上角之類的……

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容