android canvas drawText set font size from width?

前端 未结 3 1577
北恋
北恋 2020-12-12 13:36

I want to draw text on canvas of certain width using .drawtext

For example, the width of the text should always be 400px no ma

3条回答
  •  攒了一身酷
    2020-12-12 14:04

    Michael Scheper's solution seems nice but it didn't work for me, I needed to get the largest text size that is possible to draw in my view but this approach depends on the first text size you set, Every time you set a different size you'll get different results that can not say it is the right answer in every situation.

    So I tried another way:

    private float calculateMaxTextSize(String text, Paint paint, int maxWidth, int maxHeight) {
        if (text == null || paint == null) return 0;
        Rect bound = new Rect();
        float size = 1.0f;
        float step= 1.0f;    
        while (true) {
            paint.getTextBounds(text, 0, text.length(), bound);
            if (bound.width() < maxWidth && bound.height() < maxHeight) {
                size += step;
                paint.setTextSize(size);
            } else {
                return size - step;
            }
        }
    }
    

    It's simple, I increase the text size until the text rect bound dimensions are close enough to maxWidth and maxHeight, to decrease the loop repeats just change step to a bigger value (accuracy vs speed), Maybe it's not the best way to achieve this but It works.

提交回复
热议问题