使用 QPainter 的 drawText() 绘制时垂直居中文本

Center text vertically when drawing with QPainter's drawText()

我在图像上居中文本时的策略是获取该文本的边界矩形并将宽度或高度除以二。在这种情况下我也做了同样的事情。这是我创建的示例:

void CanvasWidget::paintEvent(QPaintEvent*)
{
    //Create image:
    QImage image(rect().width(), rect().height(), QImage::Format_RGB32);
    QPainter paint(&image);
    // White background
    image.fill(QColor("#FFF"));
    // set some metrics, position and the text to draw
    QFontMetrics metrics = paint.fontMetrics();
    int yposition = 100;
    QString text = "Hello world.";
    // Draw gray line to easily see if centering worked
    paint.setPen(QPen(QColor("#666"), 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin));
    paint.drawLine(0, yposition, image.width(), yposition);
    // Get rectangle
    QRect fontRect = metrics.boundingRect(text);
    // Black text
    paint.setPen(QPen(QColor("#000"), 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin));
    // Add half the height to position (note that Qt has [0,0] coordinates at the bottom of the image
    paint.drawText(4, yposition+round(((double)fontRect.height())/2.0), text);


    QPainter p(this);
    p.drawImage(rect(), image, image.rect());
    p.end();
}

这是结果 - 文本位于行下方,而不是位于行的中心:

Android:

Windows:

我使用线条根据度量矩形在文本周围画框:

预期结果是将 可见文本 恰好围绕给定的 point/line:

为了让您明白,这是我遇到的实际问题:

数字应该在行的中间,而不是下面。

我正在使用的函数 returns 大小包括 没有 的重音符号和其他大字符。如何仅针对存在 的字符获取以像素为单位的矩形

不太确定你在问什么,但如果这就是边界矩形显示错误的原因,那是因为你没有考虑字体中带有重音符号的字符,例如 é、å 等。边界从字体规格返回的矩形包括这些。

boundingRect documentation

中所述

The height of the bounding rectangle is at least as large as the value returned by height().

tightBoundingRect 情况并非如此,我希望它能提供正确的结果。