0

我正在使用以下代码NSFont使用循环查找适合宽度的大小。while是否有内置函数可以使计算更容易?

 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)



            }
           }
4

1 回答 1

0

不,没有内置功能,但你为什么要使用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
}
于 2020-04-30T10:12:16.510 回答