如何垂直对齐文本?

新手上路,请多包涵

目标:纯 Canvas 上的 Android >= 1.6。

假设我想写一个函数来绘制一个(宽度,高度)大的红色矩形,然后在里面绘制一个黑色的 Hello World 文本。我希望文本在视觉上位于矩形的中心。所以让我们试试:

 void drawHelloRectangle(Canvas c, int topLeftX,
        int topLeftY, int width, int height) {
    Paint mPaint = new Paint();
    // height of 'Hello World'; height*0.7 looks good
    int fontHeight = (int)(height*0.7);

    mPaint.setColor(COLOR_RED);
    mPaint.setStyle(Style.FILL);
    c.drawRect( topLeftX, topLeftY, topLeftX+width, topLeftY+height, mPaint);

    mPaint.setTextSize(fontHeight);
    mPaint.setColor(COLOR_BLACK);
    mPaint.setTextAlign(Align.CENTER);
    c.drawText( "Hello World", topLeftX+width/2, ????, mPaint);
}

现在我不知道在标记为 ???? 的 drawText 参数中放入什么,即我不知道如何垂直对齐文本。

就像是

??? = topLeftY + height/2 + fontHeight/2 - fontHeight/8;

似乎工作或多或少没问题,但必须有更好的方法。

原文由 Leszek 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 412
2 个回答

cxcy 为中心的示例:

 private final Rect textBounds = new Rect(); //don't new this up in a draw method

public void drawTextCentred(Canvas canvas, Paint paint, String text, float cx, float cy){
  paint.getTextBounds(text, 0, text.length(), textBounds);
  canvas.drawText(text, cx - textBounds.exactCenterX(), cy - textBounds.exactCenterY(), paint);
}

为什么 height()/2f 不一样?

exactCentre() = (top + bottom) / 2f

height()/2f = (bottom - top) / 2f

这些只会在 top0 时产生相同的结果。这可能适用于所有尺寸的某些字体,或某些尺寸的其他字体,但不是所有尺寸的所有字体。

原文由 weston 发布,翻译遵循 CC BY-SA 3.0 许可协议

textY = topLeftY + height/2 - (mPaint.descent() + mPaint.ascent()) / 2

从“基线”到“中心”的距离应该是 -(mPaint.descent() + mPaint.ascent()) / 2

原文由 QQchurch 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题