TextView文字为什么不能居中

Paint有一个方法可以拿到FontMetrics。而FontMetrics里面有:
top ,bottom,ascent,descent,lead

他们的区别是:
为了说明,这里引用辅助线baseline=0,画文字的y坐标
top:文字的最顶端离baseline的距离(ascent的极限距离负数)
ascent:文字的上端离baseline的距离(负数)
descent:文字的下端离baseline的距离(正数)
bottom:文字最下端的距离(descent的极限距离正数)
lead:上行文字descent到下行ascent的距离
下面用图来说明:


package com.sun.shine.paopao;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.util.AttributeSet;
import android.view.View;

public class TestFontMetrics extends View {

    Paint paint;

    Paint notePaint;

    public TestFontMetrics(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(150);
        notePaint = new Paint();
        notePaint.setAntiAlias(true);
        notePaint.setTextSize(20);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int noteX = 350;
        int beginX = 0;
        int baseLine = 400;
        // 画文字实例
        paint.setColor(Color.GREEN);
        canvas.drawText("jaü|攀", beginX, baseLine, paint);
        int baseLineColor = Color.BLACK;
        float width = getMeasuredWidth();
        paint.setColor(baseLineColor);

        // 画baseLine
        canvas.drawLine(0, baseLine, width, baseLine, paint);
        notePaint.setColor(baseLineColor);
        canvas.drawText("baseLine", noteX, baseLine, notePaint);

        FontMetrics fontMetrics = paint.getFontMetrics();
        float top = fontMetrics.top + baseLine;
        paint.setColor(Color.RED);
        canvas.drawLine(0, top, width, top, paint);
        notePaint.setColor(Color.RED);
        canvas.drawText("top", noteX, top, notePaint);

        float bottom = fontMetrics.bottom + baseLine;
        paint.setColor(Color.BLUE);
        canvas.drawLine(0, bottom, width, bottom, paint);
        notePaint.setColor(Color.BLUE);
        canvas.drawText("bottom", noteX, bottom, notePaint);

        float ascent = fontMetrics.ascent + baseLine;
        paint.setColor(Color.YELLOW);
        canvas.drawLine(0, ascent, width, ascent, paint);
        notePaint.setColor(Color.YELLOW);
        canvas.drawText("ascent", noteX, ascent, notePaint);

        float descent = fontMetrics.descent + baseLine;
        paint.setColor(Color.CYAN);
        canvas.drawLine(0, descent, width, descent, paint);
        notePaint.setColor(Color.CYAN);
        canvas.drawText("descent", noteX - 100, descent, notePaint);

    }
}




最后总结一下比较接近的高度应该是:descent-ascent

你可能感兴趣的:(TextView文字为什么不能居中)