I need to find the font size of a text that fits in a box.
Given my current font size, I can get the bounding rectangle of the text.
If I set some arbitrary min and max font size, I suppose I can increment or decrement my font size until I get to the given box.
I am thinking bisection method:
ChangeFontMethod(float currentFont, float reqWidth) float minFont = 1, maxFont = 1000 int tolerance = 0.001, maxIter = 1000 int n = 1 float currentWidth = textWithCurrentFont.boundingRect.Width do if currentWidth = reqWidth break else if currentWidth < reqWidth minFont = currentFont else maxFont = currentFont if maxFont - minFont < tolerance break currentFont = (minFont + maxFont)/2 currentWidth = textWithCurrentFont.boundingRect.Width n++ while n <= maxIter return currentFont
From what I read it should have logarithmic speed, but also I read that it is "slow"
Is there a better way ?
I don't know if I can improve my search by assuming a relationship between font size and font width - definitely there is one, but it's non-linear. So I don't know how to even improve the speed by a better "first guess"