我有一段很长的字符串,一个固定的字体和一个固定的矩形来绘制这个字符串。
- 如果字符串不适合矩形,我想知道适合在该矩形内的子字符串长度
- 如果字符串适合矩形,那么我想知道边界矩形的高度
我整天在网上搜索,但没找到任何资料。
// assumes myFont has been instantiated
QFontMetrics fm(myFont);
QRect bounds = fm.boundingRect("Some text here");
将边界大小与测试字符串适合的区域进行比较。
如果字符串不适合,我想知道适合该矩形的子字符串的长度
如果从boundingRect返回的矩形的边界太大,则递归地删除字符,直到宽度适合目标矩形为止。
bool bFits = false;
QString str = "String to test boundary";
QFontMetrics fm(myFont);
QRect bounds;
do
{
bounds = fm.boundingRect(str);
// Assume testBoundary is the defined QRect of the area to hold the text
if(!testBoundary.contains(bounds) && (!str.isEmpty()) )
str.chop(1);
else
bFits = true;
}while(!bFits);
int height = bounds.height();
Batman
指出了正确的方向,谢谢!顺便说一句,如果你想的话,可以使用 QFontMetrics
而不是 QPainter
。int FontUtils::FittingLength(const QString& s, QPainter &p, const QRectF& rect,
int flags/* = Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap*/)
{
QRectF r = p.boundingRect(rect, flags, s);
if (r.height() <= rect.height()) // String fits rect.
return s.length();
// Apply binary search.
QString sub;
int left = 0, right = s.length()-1;
do
{
int pivot = (left + right)>>1; // Middle point.
sub = s.mid(0, pivot+1);
r = p.boundingRect(rect, flags, sub);
if (r.height() > rect.height()) // Doesn't fit.
right = pivot-1;
else
left = pivot+1;
} while (left < right);
left++; // Length of string is one char more.
// Remove trailing word if it doesn't fit.
if ( !s.at(left).isSpace() && !s.at(left+1).isSpace() )
{
while ( (--left > 0) && !sub.at(left).isSpace() );
left++;
}
return left;
}