我想计算一个矩形的最小边界,以适应具有特定字体的字符串(多行)。
它应该看起来像这样:
FROM:
----------------------------------
|Sent when the application is about|
|to move from active to inactive |
|state. |
----------------------------------
TO:
-------------------------
|Sent when the application|
|is about to move from |
|active to inactive state.|
-------------------------
如您所见,高度保持不变,宽度变为必要的最小值。
最初我虽然可以使用boundingRectWithSize
(限制到最大宽度)首先获得所需的最小高度,然后调用boundingRectWithSize
(限制到计算的高度)来获取宽度。但这在第二步计算宽度时会产生错误的结果。它不考虑最大高度,而是简单地计算单个行字符串的宽度。
之后,我找到了一种获得正确结果的方法,但是执行此代码需要很长时间,这对我来说毫无用处:
首先计算约束宽度所需的矩形:
var objectFrame = Class.sizeOfString(string, font: objectFont, width: Double(width), height: DBL_MAX)
然后宽度:
objectFrame.size.width = Class.minWidthForHeight(string, font: objectFont, objectFrame.size.height)
使用:
class func minWidthForHeight(string: NSString, font: UIFont, height: CGFloat) -> CGFloat
{
let deltaWidth: CGFloat = 5.0
let neededHeight: CGFloat = rect.size.height
var testingWidth: CGFloat = rect.size.width
var done = false
while (done == false)
{
testingWidth -= deltaWidth
var newSize = Class.sizeOfString(string, font: font, width: Double(testingWidth), height: DBL_MAX)
if (newSize.height > neededHeight)
{
testingWidth += deltaWidth
done = true
}
}
return testingWidth
}
class func sizeOfString(string: NSString, font: UIFont, width: Double, height: Double) -> CGRect
{
return string.boundingRectWithSize(CGSize(width: width, height: height),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil)
}
它逐渐计算给定宽度的高度(每个新步骤 - 5.0 像素)并检查高度是否保持不变。一旦高度发生变化,它就会返回上一步的宽度。所以现在我们有一个边界矩形,其中特定字体的字符串完美匹配,没有任何浪费的空间。
但正如我所说,这需要很长时间来计算,尤其是同时对许多不同的字符串进行计算时。
有没有更好更快的方法来做到这一点?