我在给图片居中文本时的策略是获取该文本的边界矩形,然后将宽度或高度除以2。在这种情况下,我也是这样做的。这是我创建的一个示例:
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:
我使用线条根据度量矩形绘制文本框架: 预期的结果是将可见文本精确地居中对齐于给定的点或线: 为了让你有一个全面的了解,这就是我目前面临的实际问题:
数字应该在行的中央,而不是太低。
我使用的函数返回包括重音和其他大字符在内的尺寸,而这些字符并不存在。如何仅获取存在的字符所占的像素矩形?