drawText实现文字居中绘制

方法参数解读

/**
 * 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 origin of the text being drawn
 * @param paint The paint used for the text (e.g. color, size, style)
 */
第二个参数:baseLine 的 x值
第三个参数:baseLine 的 y值
public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) {} 参数解读

方法一

首先自己动手做实验,自己定一个baseline,然后把文字画上去,再画上FontMetrics的几条线。FontMetrics里是字体图样的信息,有float型和int型的版本,都可以从Paint中获取。它的每个成员数值都是以baseline为基准计算的,所以负值表示在baseline之上。

Rect targetRect = new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight());  //文字在 targetRect 居中
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStrokeWidth(3);
paint.setTextSize(80);
String testString = "测试:ijkJQKA:1234";
paint.setColor(Color.BLACK);
canvas.drawRect(targetRect, paint);
paint.setColor(Color.RED);
Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
// 转载请注明出处:http://blog.csdn.net/hursing
//int baseline = targetRect.centerY() - (fontMetrics.bottom + fontMetrics.top) / 2;一样
int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2;
paint.setTextAlign(Paint.Align.CENTER); //注意,drawText 对应改为传入targetRect.centerX()
canvas.drawText(testString, targetRect.centerX(), baseline, paint);

核心代码:

*写法1
    paint.setTextAlign(Paint.Align.CENTER); //注意,drawText对应改为传入targetRect.centerX()
    canvas.drawText(testString, targetRect.centerX(), baseline, paint);
*写法2
    Rect mTextRect = new Rect();
    paint.getTextBounds(testString, 0, testString.length(), mTextRect);
    int x = targetRect.centerX() - mTextRect.centerX();
    canvas.drawText(testString, x, baseline, paint);

方法二

  1. init 中通过制定的 Paint 对象计算 mTextBound
mBackPaint.setStyle(Style.FILL);
mBackPaint.setTextScaleX(2f);
mBackPaint.setColor(Color.BLACK);   // 绘画字体的颜色
mBackPaint.setTextSize(30);
mBackPaint.getTextBounds(mText, 0, mText.length(), mTextBound);
  1. 在 onDraw 中
//控制好+-号, 计算width时: 计算height时:
canvas.drawText(mText, (getWidth() - mTextBound.width()) / 2
    ,(getHeight() + mTextBound.height()) / 2, mBackPaint);

参考资料

  • Android Canvas drawText实现中文垂直居中

你可能感兴趣的:(drawText实现文字居中绘制)