简体   繁体   English

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

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

My strategy when centering text on images is to get bounding rectangle for that text and divide width or height by two. 将文字放在图像上居中时,我的策略是获取该文字的边界矩形并将宽度或高度除以2。 I did the same in this case. 在这种情况下,我也做同样的事情。 This is example I have created: 这是我创建的示例:

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();
}

This is the result - the text is under line instead centered on the line: 这就是结果-文本在行下而不是行中:

Android: 安卓:
图片描述
Windows: 视窗:
图片描述

I used lines to draw frame around the text based on metrics rectangle: 我使用线根据度量矩形在文本周围绘制框架:

图片描述

Intended result was to center visible text exactly around the given point/line: 预期结果是将可见文本恰好围绕给定点/线居中:

图片描述

To put you in perspective, this is the actual problem I am having: 为了让您更直观,这是我遇到的实际问题:
图片描述
The numbers should be in the middle of the lines, not so much below. 数字应位于行的中间,而不是下方。

The function I am using returns size including accents and other big characters that aren't there . 该功能我使用的回报大小,包括口音和其他大字符不存在 How do I get the rectangle in pixels only for characters that are there ? 如何仅针对存在的字符获取以像素单位的矩形?

Not quite sure what you're asking, but if it's why does the bounding rect appear wrong, it's because you're not taking into account characters that have accents in the font such as é, å etc. The bounding rect returned from font metrics includes these. 不太清楚您要问的是什么,但是如果这就是为什么边界rect出现错误,那是因为您没有考虑字体中带有重音的字符,例如é,å等。字体大小返回的边界rect包括这些。

As it states in the boundingRect documentation boundingRect文档中所述

The height of the bounding rectangle is at least as large as the value returned by height(). 边界矩形的高度至少与height()返回的值一样大。

This is not the case for tightBoundingRect that will, I expect, provide the right result. 我希望, tightBoundingRect不会提供正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM