Hi,
I am trying to understand the differences between
fontmetrics.horizontalAdvance(str) and fontmetrics.boundingRect(str).width().
I understand it's related to kerning, but with my experiments, the bounding rect just doesnt "bound" the string.
Also, with monospaced fonts kerning should not be a concern, right?
Consider this code:
{
fixedfont.setPointSize(9);
QString str
= "abcdefghijk 0123456789";
int a = fontmetrics.horizontalAdvance(str);
int b = fontmetrics.boundingRect(str).width();
int c = fontmetrics.averageCharWidth() * str.length();
assert(b == c);
pixmap.fill(Qt::white);
painter.setFont(fixedfont);
painter.
drawText(QPoint(0,fontmetrics.
height()), str
);
pixmap.save("fontm.bmp", "bmp");
}
{
QFont fixedfont = QFontDatabase::systemFont(QFontDatabase::FixedFont);
fixedfont.setPointSize(9);
QFontMetrics fontmetrics = QFontMetrics(fixedfont);
QString str = "abcdefghijk 0123456789";
int a = fontmetrics.horizontalAdvance(str);
int b = fontmetrics.boundingRect(str).width();
int c = fontmetrics.averageCharWidth() * str.length();
assert(b == c);
QPixmap pixmap(QSize(b, fontmetrics.height()));
pixmap.fill(Qt::white);
QPainter painter(&pixmap);
painter.setFont(fixedfont);
painter.drawText(QPoint(0,fontmetrics.height()), str);
pixmap.save("fontm.bmp", "bmp");
}
To copy to clipboard, switch view to plain text mode
Whereas horizontalAdvance gives the correct result:
gG9br5g.png
boundingRect.width() truncates the text:
h03fhfe.png
I would understand if HA had some extra space at the end. But as is, BR just doesnt bound the text. Why not?
In other words, I dont understand why with a fixed-width font, averageCharWidth * str.length() doesnt equal the pixels the string occupies when drawn at (0,0).
Bookmarks