Rewriting file names according to the available screen space
In general case I would to get text_width and container_width, then calculate new_string_length=container_width/text_width*length, than setup increase or decrease text, depending on result_text_width > container_width  and do the loop like yours.

This is really needed only if strings have a very big size.