【发布时间】:2016-01-13 10:26:23
【问题描述】:
在图像上居中文本时,我的策略是获取该文本的边界矩形并将宽度或高度除以 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:
我使用线条在基于度量矩形的文本周围绘制框架:
预期结果是将可见文本精确地围绕给定点/线居中:
为了让您正确看待,这是我遇到的实际问题:
数字应该在行的中间,而不是在下面。
我使用的函数返回大小,包括重音和其他不存在的大字符。如何仅针对存在的字符获取以像素为单位的矩形?
【问题讨论】:
标签: qt qpainter qfontmetrics