我已经尝试了在 StackOverflow 上找到的所有内容,但没有任何效果。我需要为任何可用的/随机UIFont计算 boundingRect 的高度。
代码很简单(我修改了一些代码以提高可读性):
let ps = NSMutableParagraphStyle()
ps.lineBreakMode = NSLineBreakMode.byWordWrapping
ps.alignment = NSTextAlignment.center
ps.lineSpacing = 0
ps.paragraphSpacingBefore = 0
ps.paragraphSpacing = 0
let myRandomFont = geMyRandomFont(name: randomFontName, size: myFontSize)
let attrParams = [
NSAttributedString.Key.font: myRandomFont,
NSAttributedString.Key.paragraphStyle: ps
] as [NSAttributedString.Key : Any]
let ns = NSString(string: text)
let toUseForDrawingBounds = ns.boundingRect(
with: CGSize(width: boundsSize.width, height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: attrParams,
context: nil
)
在极少数情况下(对于某些 UIFonts)它可以正常工作,但对于大多数其他字体来说, toUseForDrawingBounds.height几乎总是 1 个空白行太大。(我的输入字符串文本总是用whitespacesAndNewlines修剪)
编辑 2:经过一些测试,我注意到情况并非如此。对于每个 UIFont(字体大小和文本的不同组合),返回的高度可能会过大 1 个空白行。当我计算行数(toUseForDrawingBounds.height / font.lineHeight)时,我清楚地看到有时返回的行数太多了。
我已经尝试过使用(sizeToFit 等)UITextViews、UILabels 等的技巧(StackOverflow)。没有任何效果。有任何想法吗?
编辑:举一个清晰的例子,看看附加的图像。黄色矩形约。表示返回toUseForDrawingBounds边界。我需要适当的边界高度,以便可以垂直居中绘制文本。