[英]Center text vertically when drawing with QPainter's drawText()
将文字放在图像上居中时,我的策略是获取该文字的边界矩形并将宽度或高度除以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();
}
这就是结果-文本在行下而不是行中:
安卓:
视窗:
我使用线根据度量矩形在文本周围绘制框架:
预期结果是将可见文本恰好围绕给定点/线居中:
为了让您更直观,这是我遇到的实际问题:
数字应位于行的中间,而不是下方。
该功能我使用的回报大小,包括口音和其他大字符不存在 。 如何仅针对存在的字符获取以像素为单位的矩形?
不太清楚您要问的是什么,但是如果这就是为什么边界rect出现错误,那是因为您没有考虑字体中带有重音的字符,例如é,å等。字体大小返回的边界rect包括这些。
边界矩形的高度至少与height()返回的值一样大。
我希望, tightBoundingRect不会提供正确的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.