As what you are modeling is difficult, especially with line breaks, then your initial suggestion to try all sizes goes in the right line, especially if it needs to be accurate.
However, instead of checking each value, you can use binary search to find the appropriate font size. You know that the size is somewhere between 1 and 100 (your upper range). Using binary search, each test sets the font size and checks the resulting layout. If the text is too large, then we are looking for the lower half of the current range of possible values. If the font size is suitable, then we are looking for the upper half. Your search will use no more than 7 attempts (100 journal databases 2 are rounded up), this will be exact, finding the largest size without moving, and it will be flexible if you need to add additional requirements later, for example, a combination of fonts or more stringent restrictions on the layout.
I assume that you are using a text component that performs line breaks, and that you can set the maximum width to 400. Thus, you set the font size and it makes a layout that allows you to return the desired height by laying out the text within the specified width.
You can use the hints to try to quickly bring the algorithm to the result, for example, to make the first assumption close to the expected size, but text rendering is quick, which increase the performance may not be worth the effort of implementation.
See Wikipedia - Binary Search Algorithm
mdma source share