1. 程式人生 > >Android繪制文字時垂直居中

Android繪制文字時垂直居中

void 中心 text lac blog clas get metrics 居中

canvas.drawText(String text, float x, float y, Paint paint);

是Android中繪制文本的方法,其中的x代表文字繪制時在X軸的起始點,而y是在Y軸繪制時,文字的 baseline,不是文字的中心點也不是文字的底部。

下面代碼根據繪制的Y軸中心點centerY,算出了baseline,top,bottom,ascent和descent

    @Override
    protected void onDraw(Canvas canvas) {

        int top = mPaint.getFontMetricsInt().top;
        
int bottom = mPaint.getFontMetricsInt().bottom; int ascent = mPaint.getFontMetricsInt().ascent; int descent = mPaint.getFontMetricsInt().descent; int baselineY =centerY + (bottom-top)/2 - bottom; top = baselineY + top; bottom = baselineY + bottom; ascent
= baselineY + ascent; descent = baselineY + descent; mPaint.setColor(Color.GREEN); canvas.drawText(text, 100, baselineY, mPaint); canvas.drawLine(0, centerY, getMeasuredWidth(), centerY, mPaint); mPaint.setStrokeWidth(2); mPaint.setColor(Color.BLACK); canvas.drawLine(
0, top, getMeasuredWidth(), top, mPaint); mPaint.setColor(Color.YELLOW); canvas.drawLine(0, ascent, getMeasuredWidth(), ascent, mPaint); mPaint.setColor(Color.RED); canvas.drawLine(0, baselineY, getMeasuredWidth(), baselineY, mPaint); mPaint.setColor(Color.YELLOW); canvas.drawLine(0, descent, getMeasuredWidth(), descent, mPaint); mPaint.setColor(Color.BLACK); canvas.drawLine(0, bottom, getMeasuredWidth(), bottom, mPaint); }

Android繪制文字時垂直居中