Android自定义View以中心点(居中)绘制文字drawText

    /**
     * 以中心点绘制文字
     *
     * @param canvas
     * @param centerX
     * @param centerY
     * @param text
     * @param paint
     */
    private void drawTextWithCenterPoint(Canvas canvas, int centerX, int centerY, String text, Paint paint) {
        //获取文本的宽度,但是是一个比较粗略的结果
        float textWidth = paint.measureText(text);
        //文字度量
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        //得到基线的位置
        float baselineY = centerY + (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
        //绘制
        canvas.drawText(text, centerX - textWidth / 2, baselineY, paint);
    }
    /**
     * 竖直居中绘制文字
     *
     * @param canvas
     * @param centerX
     * @param centerY
     * @param text
     * @param paint
     */
    private void drawTextCenterInVertical(Canvas canvas, int centerX, int centerY, String text, Paint paint) {
        //文字度量
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        //得到基线的位置
        float baselineY = centerY + (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom;
        //绘制
        canvas.drawText(text, centerX, baselineY, paint);
    }

你可能感兴趣的:(自定义View,Android基础)