File indexing completed on 2023-11-26 04:09:33
0001 /* 0002 SPDX-FileCopyrightText: 2005, 2009 Albert Astals Cid <aacid@kde.org> 0003 0004 SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL 0005 */ 0006 0007 #include "kfontutils.h" 0008 0009 // own 0010 #include "kfourinline_debug.h" 0011 // Qt 0012 #include <QFont> 0013 // Std 0014 #include <limits> 0015 0016 qreal KFontUtils::adaptFontSize(QGraphicsTextItem *string, qreal width, qreal height, qreal maxFontSize, qreal minFontSize, qreal precision) 0017 { 0018 qreal size = maxFontSize; 0019 QRectF boundingRect; 0020 // Guard for avoiding possible infinite loop 0021 qreal lowerBound = 0; 0022 qreal higherBound = std::numeric_limits<double>::max(); 0023 int count = 0; 0024 0025 // Loop until found a point size that makes the text fit in the rectangle but 0026 // don't have more than precision pixels of unused space in any axys. 0027 while (count < 20) { 0028 QFont f = string->font(); 0029 f.setPointSizeF(size); 0030 string->setFont(f); 0031 string->setTextWidth(width); 0032 boundingRect = string->boundingRect(); 0033 // Error painting the text, return -1 0034 if (boundingRect.width() == 0 || boundingRect.height() == 0) { 0035 return -1; 0036 } 0037 // Text doesn't fit in rectangle or has too much unused space, adjust size 0038 else if (boundingRect.height() > height || boundingRect.height() < height - precision) { 0039 if (boundingRect.width() > width || boundingRect.height() > height) 0040 higherBound = qMin(higherBound, size); 0041 else 0042 lowerBound = qMax(lowerBound, size); 0043 0044 if (lowerBound > 0 && higherBound < std::numeric_limits<double>::max()) { 0045 size = (lowerBound + higherBound) / 2; 0046 } else { 0047 size = (height / boundingRect.height()) * size; 0048 } 0049 0050 count++; 0051 } 0052 // Text fits correctly 0053 else { 0054 break; 0055 } 0056 } 0057 0058 // Assure to return a value between minimum and maximum values. 0059 if (size < minFontSize) 0060 return minFontSize; 0061 else if (size > maxFontSize) 0062 return maxFontSize; 0063 else 0064 return size; 0065 } 0066 0067 qreal KFontUtils::adaptFontSize(QGraphicsTextItem *text, const QSizeF &availableSize, qreal maxFontSize, qreal minFontSize, qreal precision) 0068 { 0069 return adaptFontSize(text, availableSize.width(), availableSize.height(), maxFontSize, minFontSize, precision); 0070 }