Auto Scale TextView Text to Fit within Bounds

后端 未结 30 2875
囚心锁ツ
囚心锁ツ 2020-11-21 05:49

I\'m looking for an optimal way to resize wrapping text in a TextView so that it will fit within its getHeight and getWidth bounds. I\'m not simply looking for

30条回答
  •  再見小時候
    2020-11-21 06:08

    I just created the following method (based on the ideas of Chase) which might help you if you want to draw text to any canvas:

    private static void drawText(Canvas canvas, int xStart, int yStart,
            int xWidth, int yHeigth, String textToDisplay,
            TextPaint paintToUse, float startTextSizeInPixels,
            float stepSizeForTextSizeSteps) {
    
        // Text view line spacing multiplier
        float mSpacingMult = 1.0f;
        // Text view additional line spacing
        float mSpacingAdd = 0.0f;
        StaticLayout l = null;
        do {
            paintToUse.setTextSize(startTextSizeInPixels);
            startTextSizeInPixels -= stepSizeForTextSizeSteps;
            l = new StaticLayout(textToDisplay, paintToUse, xWidth,
                    Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
        } while (l.getHeight() > yHeigth);
    
        int textCenterX = xStart + (xWidth / 2);
        int textCenterY = (yHeigth - l.getHeight()) / 2;
    
        canvas.save();
        canvas.translate(textCenterX, textCenterY);
        l.draw(canvas);
        canvas.restore();
    }
    

    This could be used e.g. in any onDraw() method of any custom view.

提交回复
热议问题