Divide an conquer:
You could reduce the number of passes in your brute force method:
lets say your preferred (maximum) font size is 40 and you have a minimum font size of 0
if(40 == false && 0 == true)
- 20=true //divide possibilities in half with each guess
- 30=false
- 25=true
- 27=true
- 28=false
- so 27 wins
In what ways is this better?
this took 6 guesses instead of 13, and even if 20, 12, or 39 were the right answer it would always take about 6 guesses. so not only is it fewer guesses most of the time, it's more consistent which is important for user experience.
i think the number of guess it takes when dividing ints by half each time is the square root of the range you are looking in plus one. Math.sqroot(40-0) + 1 (That's just a guess, feel free to correct me.)
your minimum font size is probably not 0 so increasing this would speed up the search for an answer.
Illustration:
It's like playing Guess Who, players who ask "does your name have an A" and cuts the possibilities in half no matter what you answer typically finds the answer faster than the player who asks about 1 character each turn "is your name Sam" "is your name Alex"
Alternative: starting with a good guess, then testing for accuracy
I would also promote working in some logic to use the result provided by Daren's answer using fontMetrics as a good starting guess and then test it, if it fits test +2 if it doesn't fit test -2; if the new test fits test the 1 you skipped and you will know your answer, if not try moving another 2 and so on, but ideally the fontMetrics answer isn't more than 4 far off...
I suspect this will produce the fastest average results of actual use cases.
assuming you want an int and assuming the font metrics inaccuracies are minimal this will probably only take 2 or 3 guesses.