QPainter :: drawText,为每个字符获取边界框 [英] QPainter::drawText, get bounding boxes for each character

查看:1355
本文介绍了QPainter :: drawText,为每个字符获取边界框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用QPainter在QImage上绘制多行文本。但是,我还需要在每个字符的边框周围显示一个彩色矩形。

I'm using QPainter to draw multiline text on QImage. However, I also need to display a colored rectangle around each character's bounding box.

所以我需要知道每个字符在绘制时的边界框。

So I need to know the bounding box that each character had when being drawn.

例如,对于

painter.drawText(QRect(100, 100, 200, 200), Qt::TextWordWrap, "line\nline2", &r);

我需要得到10个矩形,考虑换行,换行,标签等。

I would need to get 10 rectangles, taking into account newlines, word-wrap, tabs, etc.

例如,第二个'l'的矩形将位于第一个'l',而不是在'e'的右边。

For example, the rectangle of the second 'l' would be below the rectangle of the first 'l', instead of being to the right of 'e', because of the newline.

这个图片中的红色矩形的坐标(我用手把它们放在一起,所以他们不是真正的位置):

Something like the coordinates of the red rectangles in this picture (I've put them by hand so they're not really the correct positions):

推荐答案

这可能不是最好的解决方案,但它是我能想到的最好的解决方案。

This may not be the best solution, but it's the best one I can think of.

我相信你必须自己。也就是说,不是绘制文本块,而是一次绘制一个字符。然后你可以使用QFontMetrics得到每个字符的边框。

I believe you will have to "do it yourself". That is, instead of drawing a block of text, draw each character one at a time. Then you can use QFontMetrics to get the bounding box of each character.

这是一个小工作,但不是太糟糕。类似的东西(伪代码,而不是代码):

It's a little work, but not too bad. Something like (pseudo code, not code):

QFontMetrics fm(myFont, paintDevice);
int x = startX;
int y = startY;
for (unsigned int i = 0; i < numChars; i++)
{
    char myChar = mystr[i];  // get character to print/bound
    QRect rect = fm.boundingRect( myChar );   // get that char's bounding box
    painter.drawText(x, y, Qt::TextWordWrap, mystr[i], &r);  // output char
    painter.drawRect(...); // draw char's bounding box using 'rect'
    x += rect.width();     // advance current position horizontally

    // TODO:
    // if y > lineLen      // handle cr
    //     x = startX;
    //     y += line height

}

out QFontMetrics,它有一些不同的方法来获取边界框,最小边界框等。

Check out QFontMetrics, it has a number of different methods for getting bounding boxes, minimum bounding boxes, etc.

QFontMetrics 4.7

啊...我现在看到你使用的重载返回实际边界rect。你可以使用它,如果你喜欢跳过QFontMetrics,否则整个算法是一样的。

Ahhh... I see now that the overload you're using returns the actual bounding rect. You can just use that and skip the QFontMetrics if you like - otherwise the overall algorithm is the same.

这篇关于QPainter :: drawText,为每个字符获取边界框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆