Finding NSFont Size to Fit a particular width

220 Views Asked by At

I'm using the following code to find an NSFont size to fit a Width using a while loop.Is there an inbuilt function to make the computation easier?

 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)



            }
           }
1

There are 1 best solutions below

3
Loengard On

No, there's no inbuilt function, but why do you use while(fontsize.width==fcsize)? Shouldn't the comparison be <? Try something like this:

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
}