Search code examples
androidtextsizescreenscale

Android: Text scale to biggest possible without wrapping


I am programming an app that shows a lot of verses/poems so text wrapping is not an option for me. I would like the text to be as big as possible (doesn't have to recalculate each time a new text is shown, should just allow the biggest text to fit on the screen) without extending screen size. It should not visually scale or take longer for the text to appear.

Is this possible?

Thanks


Solution

  • I would suggest a simple search for the best point size using the largest text that you need to fit. This can be done once at start-up. (Well, maybe twice—once for landscape and once for portrait). The first step would be to initialize a Paint with the typeface you want to use for display. Then call this function to

    public void setBestTextSize(String longestText, int targetWidth, Paint paint) {
        float size = paint.getTextSize(); // initial size
        float w = paint.meaasureText(longestText);
        size = targetWidth * size / w;
        paint.setTextSize(size);
        // test if we overshot
        w = paint.measureText(longestText);
        while (w > targetWidth) {
            --size;
            paint.setTextSize(size);
            w = paint.measureText(longestText);
        }
    

    A binary search in the loop might be theoretically faster, but this should do pretty well since text width does scale approximately linearly with font size and the first step before the loop should get the size pretty close.

    An alternative approach, which deals nicely with view size changes, is shown in this thread.