Wednesday 2 December 2020

Dynamically calculate text size to fill the space of rectangle

I have rectf which is drawn in canvas, based on this rectf I have drawn simple bubble alike. I want my text should be inside this bubble.

Here is what I have tried.

I have a textPaint which is initialized with textSize 30, and I'm building static layout like this.

staticLayout = StaticLayout.Builder.obtain(text, start, end, textPaint, width)
        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        .setTextDirection(TextDirectionHeuristics.LTR)
        .setLineSpacing(0, 1.0f)
        .setIncludePad(false)
        .setEllipsizedWidth(10)
        .setEllipsize(TextUtils.TruncateAt.START)
        .setMaxLines(Integer.MAX_VALUE)
        .setBreakStrategy(Layout.BREAK_STRATEGY_SIMPLE)
        .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NONE)
        .setJustificationMode(Layout.JUSTIFICATION_MODE_NONE)
        .build()

From this static layout I'm getting my TextLayout's height as staticLayout.height

I want my text layout height should not exceed by 70% of my bounds height, so that my text will be always inside my bounds.

float maxTextLayoutHeight = bounds.height() * 0.70f;

And my actual static layout's height

height = staticLayout.height;

From these two values I recalculate text size and applied it to my text paint with following code.

annotationTextSize = (maxTextLayoutHeight / height) * 13;
annotationTextSize = annotationTextSize * 0.80f;
if (annotationTextSize < 25) annotationTextSize = 25; //Limited to min 25
if (annotationTextSize > 99) annotationTextSize = 99; //Limited to max 99
textPaint.setTextSize(annotationTextSize);

Here is some images

With small text size:

enter image description here

enter image description here

Text size looks perfect:

enter image description here

enter image description here

Text size looks bigger:

enter image description here

enter image description here

Any improved calculation will be much helpful.



from Dynamically calculate text size to fill the space of rectangle

No comments:

Post a Comment