我使用以下代码来查找NSFont
大小,以便使用while
循环来适应Width。有没有一个内置的函数可以让计算更容易?
let ratio = image.size.width/referenceimagesize!.width
let fcsize=fontsize.width*ratio
if(fontsize.width<fcsize)
{
while(fontsize.width==fcsize)
{
var newheight:CGFloat = 0;
font = NSFont(name: font!.fontName, size: font!.pointSize+1)
var fontAttributes = [NSAttributedStringKey.font: font]
fontsize = (text as NSString).size(withAttributes: fontAttributes)
}
}
不,没有内置函数,但为什么要使用while(fontsize.width==fcsize)
?比较不应该是<
吗?试试这样的东西:
func findFontSize(text: String, frameWidth: CGFloat, font: NSFont) -> CGFloat {
var textSize = text.size(withAttributes: [.font: font])
var newPointSize = font.pointSize
while textSize.width < frameWidth {
newPointSize += 1
let newFont = NSFont(name: font.fontName, size: newPointSize)!
textSize = text.size(withAttributes: [.font: newFont])
}
return newPointSize
}