android drawText居中

比较简单的东西,为了防止以后忘记,这里记录下。

注意以下几点
  1. public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint)
    这个方法中 x y坐标并不是文本左下角。x的轴线实际是 fontMetrics.baseline(新版本api中是leading),且文本部分会绘制到x轴线下方
  2. 如果需要居中绘制 当前的x轴位置 - (fontMetrics.top + fontMetrics.bottom)/2 即可。
  3. 没啥说的直接放代码:
public class CustomTextView extends View {


    private Paint paint;

    public CustomTextView(Context context) {
        super(context);
        init();
    }

    public CustomTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setTextSize(80);
        paint.setColor(Color.BLACK);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        //居中线
        float midLine = - (fontMetrics.top + fontMetrics.bottom)/2 + getMeasuredHeight()/2;
//        canvas.translate(0,150);
        //绘制x轴y轴
        //canvas.drawLine(0, 0, getMeasuredWidth(), 0, paint);
        //canvas.drawLine(0, 0, 0, getMeasuredHeight(), paint);
//        paint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText("我是测试文本", 0, midLine, paint);
        //绘制文本线格
//        paint.setColor(Color.GREEN);
//        canvas.drawLine(0, fontMetrics.top, getMeasuredWidth(), fontMetrics.top, paint);
//        paint.setColor(Color.BLUE);
//        canvas.drawLine(0, fontMetrics.ascent, getMeasuredWidth(), fontMetrics.ascent, paint);
//        paint.setColor(Color.YELLOW);
//        canvas.drawLine(0, fontMetrics.leading, getMeasuredWidth(), fontMetrics.leading, paint);
//        paint.setColor(Color.RED);
//        canvas.drawLine(0, fontMetrics.descent, getMeasuredWidth(), fontMetrics.descent, paint);
//        paint.setColor(Color.CYAN);
//        canvas.drawLine(0, fontMetrics.bottom, getMeasuredWidth(), fontMetrics.bottom, paint);
    }
}

你可能感兴趣的:(android drawText居中)