<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Inidam Leader on Medium]]></title>
        <description><![CDATA[Stories by Inidam Leader on Medium]]></description>
        <link>https://medium.com/@gladiatorkilo?source=rss-3974b7b057eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hQltJLVd0pKzksdtrFd1Jg.jpeg</url>
            <title>Stories by Inidam Leader on Medium</title>
            <link>https://medium.com/@gladiatorkilo?source=rss-3974b7b057eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:59:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gladiatorkilo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Text Sizing with AutoSizeText in Jetpack Compose]]></title>
            <link>https://medium.com/@gladiatorkilo/autosize-text-implementation-in-jetpack-compose-6b1c803eb7be?source=rss-3974b7b057eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b1c803eb7be</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[text]]></category>
            <category><![CDATA[autosize]]></category>
            <dc:creator><![CDATA[Inidam Leader]]></dc:creator>
            <pubDate>Tue, 23 May 2023 19:19:43 GMT</pubDate>
            <atom:updated>2025-08-21T11:38:36.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RzixgbpyfoOTdMN6LvjVQ.png" /><figcaption>Previews</figcaption></figure><p><strong>Typography is a cornerstone of UI/UX design</strong>, especially in mobile apps where text plays a critical role in user interaction. For a long time, Jetpack Compose lacked a built-in solution for automatic text resizing — a feature developers often had to implement manually.</p><p>But that’s finally changed. 🎉 With the introduction of the autoSize parameter in BasicText, Google has officially brought <strong>dynamic text resizing</strong> to Jetpack Compose. This feature allows text to automatically scale within its container, making UIs more responsive and adaptable across screen sizes.</p><p>While I haven’t explored it in depth yet, my initial testing revealed a few quirks — most notably:</p><ul><li><strong>Line spacing (critical flaw)</strong>: This is the most noticeable issue so far. When maxLines is greater than 1, the line spacing doesn’t scale proportionally with the resized text. The result is often cramped or visually awkward multiline text, which significantly affects readability and layout harmony.</li><li><strong>Alignment</strong>: Compared to a custom AutoSizeText solution, the auto-sized text tends to be slightly shifted toward the top-start corner of its container.</li><li><strong>Step precision</strong>: Text scaling feels a bit coarse — a finer step increment (e.g., 1px or its dp equivalent) would allow for smoother resizing transitions.</li><li><strong>Font size suggestions</strong>: On a positive note, the option to provide a list of font sizes for the system to choose from is a very welcome addition. It gives developers more flexibility and control over the rendered text.</li></ul><p>To work around these limitations — especially the <strong>line spacing issue</strong>, which can severely affect multi-line content — I’ll share a custom AutoSizeText composable later in this post. While it may appear more complex than the built-in option, it offers better control and addresses subtle rendering flaws that matter in polished UI design.</p><h3>Explore the Gist — with 70+ stars from developers around the world who’ve tried and trusted it. See the link below to dive in.</h3><h3>Key Features:</h3><ol><li><strong>Optimized Performance</strong>: Utilizes a dichotomous binary search algorithm for swift and efficient text size determination, ensuring optimal resizing without unnecessary iterations.</li><li><strong>Alignment Control</strong>: Supports six alignment values, offering precise control over horizontal and vertical text alignment within its container.</li><li><strong>Material Design 3 Harmony</strong>: Seamlessly aligns with Material Design 3 guidelines, ensuring text adheres to the aesthetic principles, enhancing your app’s visual appeal.</li><li><strong>Font Scaling Resilience</strong>: User-initiated font scaling won’t impact visual rendering, providing consistency in text display despite device font settings.</li><li><strong>Multiline Support with </strong><strong>maxLines Parameter</strong>: Introduces maxLines parameter, allowing control over the maximum visible lines within a specific space.</li></ol><h3>Getting Started with AutoSizeText:</h3><p>To integrate AutoSizeText into your Jetpack Compose app:</p><ol><li><strong>Dependency Configuration</strong>: Ensure your build.gradle includes necessary dependencies, particularly Material Design Components 3 (MDC3).</li><li><strong>Configuration Parameters</strong>: Customize AutoSizeText using parameters like minTextSize, maxTextSize, and stepGranularityTextSize to fine-tune text resizing behavior.</li></ol><h3>Code Explanation:</h3><p>The code starts by defining a composable function called AutoSizeText. This function automatically adjusts the text size to fit within given constraints, considering the ratio of line spacing to text size. The function takes several parameters that are the same as Text function, plus:</p><ul><li>The suggested font sizes to choose from</li><li>The step size for adjusting the text size</li><li>The minimum and maximum text sizes allowed</li><li>…</li></ul><p><em>AutoSizeText.kt:</em></p><pre>/*<br>MIT License<br>Copyright (c) 2024 Reda El Madini<br>Permission is hereby granted, free of charge, to any person obtaining a copy<br>of this software and associated documentation files (the &quot;Software&quot;), to deal<br>in the Software without restriction, including without limitation the rights<br>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell<br>copies of the Software, and to permit persons to whom the Software is<br>furnished to do so, subject to the following conditions:<br>The above copyright notice and this permission notice shall be included in all<br>copies or substantial portions of the Software.<br>THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR<br>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<br>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<br>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<br>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE<br>SOFTWARE.<br>*/<br><br>package com.inidamleader.ovtracker.util.compose<br><br>import android.util.Log<br>import androidx.compose.foundation.layout.BoxWithConstraints<br>import androidx.compose.foundation.layout.BoxWithConstraintsScope<br>import androidx.compose.foundation.layout.fillMaxSize<br>import androidx.compose.foundation.text.InlineTextContent<br>import androidx.compose.material3.LocalContentColor<br>import androidx.compose.material3.LocalTextStyle<br>import androidx.compose.material3.MaterialTheme<br>import androidx.compose.material3.Surface<br>import androidx.compose.material3.Text<br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.CompositionLocalProvider<br>import androidx.compose.runtime.Stable<br>import androidx.compose.runtime.remember<br>import androidx.compose.ui.Alignment<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.graphics.Color<br>import androidx.compose.ui.graphics.isSpecified<br>import androidx.compose.ui.platform.LocalDensity<br>import androidx.compose.ui.platform.LocalFontFamilyResolver<br>import androidx.compose.ui.platform.LocalLayoutDirection<br>import androidx.compose.ui.text.AnnotatedString<br>import androidx.compose.ui.text.TextLayoutResult<br>import androidx.compose.ui.text.TextMeasurer<br>import androidx.compose.ui.text.TextStyle<br>import androidx.compose.ui.text.font.FontFamily<br>import androidx.compose.ui.text.font.FontStyle<br>import androidx.compose.ui.text.font.FontWeight<br>import androidx.compose.ui.text.rememberTextMeasurer<br>import androidx.compose.ui.text.style.LineHeightStyle<br>import androidx.compose.ui.text.style.TextAlign<br>import androidx.compose.ui.text.style.TextDecoration<br>import androidx.compose.ui.text.style.TextOverflow<br>import androidx.compose.ui.tooling.preview.Preview<br>import androidx.compose.ui.unit.Density<br>import androidx.compose.ui.unit.IntSize<br>import androidx.compose.ui.unit.LayoutDirection<br>import androidx.compose.ui.unit.TextUnit<br>import androidx.compose.ui.unit.isSpecified<br>import androidx.compose.ui.unit.sp<br>import androidx.compose.ui.util.fastAll<br>import androidx.compose.ui.util.fastCoerceAtLeast<br>import androidx.compose.ui.util.fastCoerceIn<br>import androidx.compose.ui.util.fastFilter<br>import com.inidamleader.skeleton.util.compose.SuggestedFontSizesStatus.Companion.validSuggestedFontSizes<br>import com.inidamleader.skeleton.util.compose.geometry.intPxToSp<br>import com.inidamleader.skeleton.util.compose.geometry.spRoundToPx<br>import com.inidamleader.skeleton.util.compose.geometry.spToIntPx<br>import kotlin.math.min<br><br>private const val TAG = &quot;AutoSizeText&quot;<br><br>/**<br> * Composable function that automatically adjusts the text size to fit within given constraints, considering the ratio of line spacing to text size.<br> *<br> * Features:<br> *  1. Best performance: Utilizes a dichotomous binary search algorithm for swift and optimal text size determination without unnecessary iterations.<br> *  2. Alignment support: Supports six possible alignment values via the Alignment interface.<br> *  3. Material Design 3 support.<br> *  4. Font scaling support: User-initiated font scaling doesn&#39;t affect the visual rendering output.<br> *  5. Multiline Support with maxLines Parameter.<br> *<br> * @param text the text to be displayed<br> * @param modifier the [Modifier] to be applied to this layout node<br> * @param color [Color] to apply to the text. If [Color.Unspecified], and [style] has no color set,<br> * this will be [LocalContentColor].<br> * @param suggestedFontSizes The suggested font sizes to choose from (Should be sorted from smallest to largest, not empty and contains only sp text unit).<br> * @param suggestedFontSizesStatus Whether or not suggestedFontSizes is valid: not empty - contains oly sp text unit - sorted.<br> * You can check validity by invoking [List&lt;TextUnit&gt;.suggestedFontSizesStatus].<br> * @param stepGranularityTextSize The step size for adjusting the text size. this parameter is ignored if [suggestedFontSizes] is specified and [suggestedFontSizesStatus] is [SuggestedFontSizesStatus.VALID].<br> * @param minTextSize The minimum text size allowed. this parameter is ignored if [suggestedFontSizes] is specified or [suggestedFontSizesStatus] is [SuggestedFontSizesStatus.VALID].<br> * @param maxTextSize The maximum text size allowed.<br> * @param fontStyle the typeface variant to use when drawing the letters (e.g., italic).<br> * See [TextStyle.fontStyle].<br> * @param fontWeight the typeface thickness to use when painting the text (e.g., [FontWeight.Bold]).<br> * @param fontFamily the font family to be used when rendering the text. See [TextStyle.fontFamily].<br> * @param letterSpacing the amount of space to add between each letter.<br> * See [TextStyle.letterSpacing].<br> * @param textDecoration the decorations to paint on the text (e.g., an underline).<br> * See [TextStyle.textDecoration].<br> * @param alignment The alignment of the text within its container.<br> * @param overflow how visual overflow should be handled.<br> * @param softWrap whether the text should break at soft line breaks. If false, the glyphs in the<br> * text will be positioned as if there was unlimited horizontal space. If [softWrap] is false,<br> * [overflow] and TextAlign may have unexpected effects.<br> * @param maxLines An optional maximum number of lines for the text to span, wrapping if<br> * necessary. If the text exceeds the given number of lines, it will be truncated according to<br> * [overflow] and [softWrap]. It is required that 1 &lt;= [minLines] &lt;= [maxLines].<br> * @param minLines The minimum height in terms of minimum number of visible lines. It is required<br> * that 1 &lt;= [minLines] &lt;= [maxLines].<br> * insert composables into text layout. See [InlineTextContent].<br> * @param onTextLayout callback that is executed when a new text layout is calculated. A<br> * [TextLayoutResult] object that callback provides contains paragraph information, size of the<br> * text, baselines and other details. The callback can be used to add additional decoration or<br> * functionality to the text. For example, to draw selection around the text.<br> * @param style style configuration for the text such as color, font, line height etc.<br> * @param lineSpaceRatio The ratio of line spacing to text size.<br> *<br> * @author Reda El Madini - For support, contact gladiatorkilo@gmail.com<br> */<br>@Composable<br>fun AutoSizeText(<br>    text: String,<br>    modifier: Modifier = Modifier,<br>    color: Color = Color.Unspecified,<br>    suggestedFontSizes: List&lt;TextUnit&gt; = emptyList(),<br>    suggestedFontSizesStatus: SuggestedFontSizesStatus = SuggestedFontSizesStatus.UNKNOWN,<br>    stepGranularityTextSize: TextUnit = TextUnit.Unspecified,<br>    minTextSize: TextUnit = TextUnit.Unspecified,<br>    maxTextSize: TextUnit = TextUnit.Unspecified,<br>    fontStyle: FontStyle? = null,<br>    fontWeight: FontWeight? = null,<br>    fontFamily: FontFamily? = null,<br>    letterSpacing: TextUnit = TextUnit.Unspecified,<br>    textDecoration: TextDecoration? = null,<br>    alignment: Alignment = Alignment.TopStart,<br>    overflow: TextOverflow = TextOverflow.Clip,<br>    softWrap: Boolean = true,<br>    maxLines: Int = Int.MAX_VALUE,<br>    minLines: Int = 1,<br>    onTextLayout: (TextLayoutResult) -&gt; Unit = {},<br>    style: TextStyle = LocalTextStyle.current,<br>    lineSpaceRatio: Float = style.lineHeight.value / style.fontSize.value,<br>) {<br>    AutoSizeText(<br>        text = AnnotatedString(text),<br>        modifier = modifier,<br>        color = color,<br>        suggestedFontSizes = suggestedFontSizes,<br>        suggestedFontSizesStatus = suggestedFontSizesStatus,<br>        stepGranularityTextSize = stepGranularityTextSize,<br>        minTextSize = minTextSize,<br>        maxTextSize = maxTextSize,<br>        fontStyle = fontStyle,<br>        fontWeight = fontWeight,<br>        fontFamily = fontFamily,<br>        letterSpacing = letterSpacing,<br>        textDecoration = textDecoration,<br>        alignment = alignment,<br>        overflow = overflow,<br>        softWrap = softWrap,<br>        maxLines = maxLines,<br>        minLines = minLines,<br>        onTextLayout = onTextLayout,<br>        style = style,<br>        lineSpacingRatio = lineSpaceRatio,<br>    )<br>}<br><br>/**<br> * Composable function that automatically adjusts the text size to fit within given constraints using AnnotatedString, considering the ratio of line spacing to text size.<br> *<br> * Features:<br> *  Similar to AutoSizeText(String), with support for AnnotatedString.<br> *<br> * @param inlineContent a map storing composables that replaces certain ranges of the text, used to<br> * insert composables into text layout. See [InlineTextContent].<br> * @see AutoSizeText<br> */<br>@Composable<br>fun AutoSizeText(<br>    text: AnnotatedString,<br>    modifier: Modifier = Modifier,<br>    color: Color = Color.Unspecified,<br>    suggestedFontSizes: List&lt;TextUnit&gt; = emptyList(),<br>    suggestedFontSizesStatus: SuggestedFontSizesStatus = SuggestedFontSizesStatus.UNKNOWN,<br>    stepGranularityTextSize: TextUnit = TextUnit.Unspecified,<br>    minTextSize: TextUnit = TextUnit.Unspecified,<br>    maxTextSize: TextUnit = TextUnit.Unspecified,<br>    fontStyle: FontStyle? = null,<br>    fontWeight: FontWeight? = null,<br>    fontFamily: FontFamily? = null,<br>    letterSpacing: TextUnit = TextUnit.Unspecified,<br>    textDecoration: TextDecoration? = null,<br>    alignment: Alignment = Alignment.TopStart,<br>    overflow: TextOverflow = TextOverflow.Clip,<br>    softWrap: Boolean = true,<br>    maxLines: Int = Int.MAX_VALUE,<br>    minLines: Int = 1,<br>    inlineContent: Map&lt;String, InlineTextContent&gt; = mapOf(),<br>    onTextLayout: (TextLayoutResult) -&gt; Unit = {},<br>    style: TextStyle = LocalTextStyle.current,<br>    lineSpacingRatio: Float = style.lineHeight.value / style.fontSize.value,<br>) {<br>    // Change font scale to 1F<br>    val density = Density(density = LocalDensity.current.density, fontScale = 1F)<br>    CompositionLocalProvider(LocalDensity provides density) {<br>        BoxWithConstraints(<br>            modifier = modifier,<br>            contentAlignment = alignment,<br>        ) {<br>            val combinedTextStyle = LocalTextStyle.current + style.copy(<br>                color = color.takeIf { it.isSpecified } ?: style.color,<br>                fontStyle = fontStyle ?: style.fontStyle,<br>                fontWeight = fontWeight ?: style.fontWeight,<br>                fontFamily = fontFamily ?: style.fontFamily,<br>                letterSpacing = letterSpacing.takeIf { it.isSpecified } ?: style.letterSpacing,<br>                textDecoration = textDecoration ?: style.textDecoration,<br>                textAlign = if (style.textAlign == TextAlign.Justify) TextAlign.Justify<br>                else when (alignment) {<br>                    Alignment.TopStart, Alignment.CenterStart, Alignment.BottomStart -&gt; TextAlign.Start<br>                    Alignment.TopCenter, Alignment.Center, Alignment.BottomCenter -&gt; TextAlign.Center<br>                    Alignment.TopEnd, Alignment.CenterEnd, Alignment.BottomEnd -&gt; TextAlign.End<br>                    else -&gt; TextAlign.Unspecified<br>                },<br>            )<br><br>            val layoutDirection = LocalLayoutDirection.current<br>            val fontFamilyResolver = LocalFontFamilyResolver.current<br>            val textMeasurer = rememberTextMeasurer()<br>            val coercedLineSpacingRatio = lineSpacingRatio.takeIf { it.isFinite() &amp;&amp; it &gt;= 1 } ?: 1F<br>            val shouldMoveBackward: (TextUnit) -&gt; Boolean = {<br>                shouldShrink(<br>                    text = text,<br>                    textStyle = combinedTextStyle.copy(<br>                        fontSize = it,<br>                        lineHeight = it * coercedLineSpacingRatio,<br>                    ),<br>                    maxLines = maxLines,<br>                    layoutDirection = layoutDirection,<br>                    softWrap = softWrap,<br>                    density = density,<br>                    fontFamilyResolver = fontFamilyResolver,<br>                    textMeasurer = textMeasurer,<br>                )<br>            }<br><br>            val electedFontSize = remember(<br>                key1 = suggestedFontSizes,<br>                key2 = suggestedFontSizesStatus,<br>            ) {<br>                if (suggestedFontSizesStatus == SuggestedFontSizesStatus.VALID) suggestedFontSizes<br>                else suggestedFontSizes.validSuggestedFontSizes<br>            }?.let {<br>                remember(<br>                    key1 = it,<br>                    key2 = shouldMoveBackward,<br>                ) {<br>                    it.findElectedValue(shouldMoveBackward = shouldMoveBackward)<br>                }<br>            } ?: run {<br>                val candidateFontSizesIntProgress = rememberCandidateFontSizesIntProgress(<br>                    density = density,<br>                    intSize = IntSize(constraints.maxWidth, constraints.maxHeight),<br>                    maxTextSize = maxTextSize,<br>                    minTextSize = minTextSize,<br>                    stepGranularityTextSize = stepGranularityTextSize,<br>                )<br>                remember(<br>                    key1 = candidateFontSizesIntProgress,<br>                    key2 = shouldMoveBackward,<br>                ) {<br>                    candidateFontSizesIntProgress.findElectedValue(<br>                        transform = { density.intPxToSp(it) },<br>                        shouldMoveBackward = shouldMoveBackward,<br>                    )<br>                }<br>            }<br><br>            if (electedFontSize == 0.sp) Log.w(<br>                TAG,<br>                &quot;&quot;&quot;The text cannot be displayed. Please consider the following options:<br>                      |  1. Providing &#39;suggestedFontSizes&#39; with smaller values that can be utilized.<br>                      |  2. Decreasing the &#39;stepGranularityTextSize&#39; value.<br>                      |  3. Adjusting the &#39;minTextSize&#39; parameter to a suitable value and ensuring the overflow parameter is set to &quot;TextOverflow.Ellipsis&quot;.<br>                    &quot;&quot;&quot;.trimMargin(),<br>            )<br><br>            Text(<br>                text = text,<br>                overflow = overflow,<br>                softWrap = softWrap,<br>                maxLines = maxLines,<br>                minLines = minLines,<br>                inlineContent = inlineContent,<br>                onTextLayout = onTextLayout,<br>                style = combinedTextStyle.copy(<br>                    fontSize = electedFontSize,<br>                    lineHeight = electedFontSize * coercedLineSpacingRatio,<br>                ),<br>            )<br>        }<br>    }<br>}<br><br>private fun BoxWithConstraintsScope.shouldShrink(<br>    text: AnnotatedString,<br>    textStyle: TextStyle,<br>    maxLines: Int,<br>    layoutDirection: LayoutDirection,<br>    softWrap: Boolean,<br>    density: Density,<br>    fontFamilyResolver: FontFamily.Resolver,<br>    textMeasurer: TextMeasurer,<br>) = textMeasurer.measure(<br>    text = text,<br>    style = textStyle,<br>    overflow = TextOverflow.Clip,<br>    softWrap = softWrap,<br>    maxLines = maxLines,<br>    constraints = constraints,<br>    layoutDirection = layoutDirection,<br>    density = density,<br>    fontFamilyResolver = fontFamilyResolver,<br>).hasVisualOverflow<br><br>@Stable<br>@Composable<br>private fun rememberCandidateFontSizesIntProgress(<br>    density: Density,<br>    intSize: IntSize,<br>    minTextSize: TextUnit = TextUnit.Unspecified,<br>    maxTextSize: TextUnit = TextUnit.Unspecified,<br>    stepGranularityTextSize: TextUnit = TextUnit.Unspecified,<br>): IntProgression {<br>    val max = remember(key1 = maxTextSize, key2 = intSize) {<br>        min(intSize.width, intSize.height).let { max -&gt;<br>            maxTextSize.takeIf { it.isSp }?.let { density.spRoundToPx(it) }?.fastCoerceIn(0, max) ?: max<br>        }<br>    }<br><br>    val min = remember(key1 = minTextSize, key2 = max) {<br>        minTextSize.takeIf { it.isSp }?.let { density.spToIntPx(it) }?.fastCoerceIn(0, max) ?: 0<br>    }<br><br>    val step = remember(<br>        key1 = min,<br>        key2 = max,<br>        key3 = stepGranularityTextSize,<br>    ) {<br>        stepGranularityTextSize.takeIf { it.isSp }?.let { density.spToIntPx(it) }?.fastCoerceIn(1, max - min) ?: 1<br>    }<br><br>    return remember(key1 = min, key2 = max, key3 = step) {<br>        min..max step step<br>    }<br>}<br><br>// This function works by using a binary search algorithm<br>internal fun &lt;T&gt; List&lt;T&gt;.findElectedValue(shouldMoveBackward: (T) -&gt; Boolean) = run {<br>    indices.findElectedValue(<br>        transform = { this[it] },<br>        shouldMoveBackward = shouldMoveBackward,<br>    )<br>}<br><br>// This function works by using a binary search algorithm<br>private fun &lt;T&gt; IntProgression.findElectedValue(<br>    transform: (Int) -&gt; T,<br>    shouldMoveBackward: (T) -&gt; Boolean,<br>) = run {<br>    var low = first / step<br>    var high = last / step<br>    while (low &lt;= high) {<br>        val mid = low + (high - low) / 2<br>        if (shouldMoveBackward(transform(mid * step))) high = mid - 1<br>        else low = mid + 1<br>    }<br>    transform((high * step).fastCoerceAtLeast(first * step))<br>}<br><br>enum class SuggestedFontSizesStatus {<br>    VALID, INVALID, UNKNOWN;<br><br>    companion object {<br>        val List&lt;TextUnit&gt;.suggestedFontSizesStatus: SuggestedFontSizesStatus<br>            get() = if (isNotEmpty() &amp;&amp; fastAll { it.isSp } &amp;&amp; sortedBy { it.value } == this) VALID<br>            else INVALID<br><br>        val List&lt;TextUnit&gt;.validSuggestedFontSizes: List&lt;TextUnit&gt;?<br>            get() = takeIf { it.isNotEmpty() } // Optimization: empty check first to immediately return null<br>                ?.fastFilter { it.isSp }?.takeIf { it.isNotEmpty() }?.sortedBy { it.value }<br>    }<br>}<br><br>@Preview(widthDp = 200, heightDp = 100)<br>@Preview(widthDp = 200, heightDp = 30)<br>@Preview(widthDp = 60, heightDp = 30)<br>@Composable<br>private fun Preview1() {<br>    MaterialTheme {<br>        Surface(color = MaterialTheme.colorScheme.primary) {<br>            AutoSizeText(<br>                text = &quot;This is a bunch of text that will be auto sized&quot;,<br>                modifier = Modifier.fillMaxSize(),<br>                alignment = Alignment.CenterStart,<br>                style = MaterialTheme.typography.bodyMedium,<br>            )<br>        }<br>    }<br>}<br><br>@Preview(widthDp = 200, heightDp = 100)<br>@Preview(widthDp = 200, heightDp = 30)<br>@Preview(widthDp = 60, heightDp = 30)<br>@Composable<br>private fun Preview2() {<br>    MaterialTheme {<br>        Surface(color = MaterialTheme.colorScheme.secondary) {<br>            AutoSizeText(<br>                text = &quot;This is a bunch of text that will be auto sized&quot;,<br>                modifier = Modifier.fillMaxSize(),<br>                minTextSize = 14.sp,<br>                alignment = Alignment.CenterStart,<br>                overflow = TextOverflow.Ellipsis,<br>                style = MaterialTheme.typography.bodyMedium,<br>            )<br>        }<br>    }<br>}<br><br>@Preview(widthDp = 200, heightDp = 100)<br>@Preview(widthDp = 200, heightDp = 30)<br>@Preview(widthDp = 60, heightDp = 30)<br>@Composable<br>private fun Preview3() {<br>    MaterialTheme {<br>        Surface(color = MaterialTheme.colorScheme.tertiary) {<br>            AutoSizeText(<br>                text = &quot;This is a bunch of text that will be auto sized&quot;,<br>                modifier = Modifier.fillMaxSize(),<br>                alignment = Alignment.Center,<br>                maxLines = 1,<br>                style = MaterialTheme.typography.bodyMedium,<br>            )<br>        }<br>    }<br>}<br><br>@Preview(widthDp = 100, heightDp = 50)<br>@Preview(widthDp = 50, heightDp = 100)<br>@Composable<br>private fun Preview4() {<br>    MaterialTheme {<br>        Surface(color = MaterialTheme.colorScheme.error) {<br>            AutoSizeText(<br>                text = &quot;m&quot;,<br>                modifier = Modifier.fillMaxSize(),<br>                alignment = Alignment.Center,<br>                style = MaterialTheme.typography.bodyMedium,<br>                lineSpaceRatio = 1F,<br>            )<br>        }<br>    }<br>}<br><br>@Preview(widthDp = 100, heightDp = 50)<br>@Preview(widthDp = 50, heightDp = 100)<br>@Composable<br>private fun Preview5() {<br>    MaterialTheme {<br>        Surface(color = MaterialTheme.colorScheme.error) {<br>            AutoSizeText(<br>                text = &quot;y&quot;,<br>                modifier = Modifier.fillMaxSize(),<br>                alignment = Alignment.Center,<br>                style = MaterialTheme.typography.bodyMedium.copy(<br>                    lineHeightStyle = LineHeightStyle(<br>                        alignment = LineHeightStyle.Alignment.Center,<br>                        trim = LineHeightStyle.Trim.Both,<br>                    )<br>                ),<br>            )<br>        }<br>    }<br>}</pre><p><em>density.kt:</em></p><pre>package com.inidamleader.ovtracker.util.compose.geometry<br><br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.geometry.Offset<br>import androidx.compose.ui.geometry.Size<br>import androidx.compose.ui.geometry.isSpecified<br>import androidx.compose.ui.platform.LocalDensity<br>import androidx.compose.ui.unit.Density<br>import androidx.compose.ui.unit.Dp<br>import androidx.compose.ui.unit.DpOffset<br>import androidx.compose.ui.unit.DpSize<br>import androidx.compose.ui.unit.IntOffset<br>import androidx.compose.ui.unit.IntSize<br>import androidx.compose.ui.unit.TextUnit<br>import androidx.compose.ui.unit.dp<br>import androidx.compose.ui.unit.isSpecified<br>import kotlin.math.roundToInt<br><br>// Those functions are designed to be used in lambdas<br><br>// DP<br>fun Density.dpToSp(dp: Dp) = if (dp.isSpecified) dp.toSp() else TextUnit.Unspecified<br><br>fun Density.dpToFloatPx(dp: Dp) = if (dp.isSpecified) dp.toPx() else Float.NaN<br><br>fun Density.dpToIntPx(dp: Dp) = if (dp.isSpecified) dp.toPx().toInt() else 0<br><br>fun Density.dpRoundToPx(dp: Dp) = if (dp.isSpecified) dp.roundToPx() else 0<br><br>@Composable<br>fun Dp.toSp() = LocalDensity.current.dpToSp(this)<br><br>@Composable<br>fun Dp.toFloatPx() = LocalDensity.current.dpToFloatPx(this)<br><br>@Composable<br>fun Dp.toIntPx() = LocalDensity.current.dpToIntPx(this)<br><br>@Composable<br>fun Dp.roundToPx() = LocalDensity.current.dpRoundToPx(this)<br><br>fun Dp.toRecDpSize() = if (isSpecified) DpSize(this, this) else DpSize.Unspecified<br><br>fun Dp.toRecDpOffset() = if (isSpecified) DpOffset(this, this) else DpOffset.Unspecified<br><br><br>// TEXT UNIT<br>fun Density.spToDp(sp: TextUnit) = if (sp.isSpecified) sp.toDp() else Dp.Unspecified<br><br>fun Density.spToFloatPx(sp: TextUnit) = if (sp.isSpecified) sp.toPx() else Float.NaN<br><br>fun Density.spToIntPx(sp: TextUnit) = if (sp.isSpecified) sp.toPx().toInt() else 0<br><br>fun Density.spRoundToPx(sp: TextUnit) = if (sp.isSpecified) sp.roundToPx() else 0<br><br>@Composable<br>fun TextUnit.toDp() = LocalDensity.current.spToDp(this)<br><br>@Composable<br>fun TextUnit.toFloatPx() = LocalDensity.current.spToFloatPx(this)<br><br>@Composable<br>fun TextUnit.toIntPx() = LocalDensity.current.spToIntPx(this)<br><br>@Composable<br>fun TextUnit.roundToPx() = LocalDensity.current.spRoundToPx(this)<br><br><br>// FLOAT<br>fun Density.floatPxToDp(px: Float) = if (px.isFinite()) px.toDp() else Dp.Unspecified<br><br>fun Density.floatPxToSp(px: Float) = if (px.isFinite()) px.toSp() else TextUnit.Unspecified<br><br>@Composable<br>fun Float.toDp() = LocalDensity.current.floatPxToDp(this)<br><br>@Composable<br>fun Float.toSp() = LocalDensity.current.floatPxToSp(this)<br><br>fun Float.toIntPx() = if (isFinite()) toInt() else 0<br><br>fun Float.roundToPx() = if (isFinite()) roundToInt() else 0<br><br>fun Float.toRecSize() = if (isFinite()) Size(this, this) else Size.Unspecified<br><br>fun Float.toRecOffset() = if (isFinite()) Offset(this, this) else Offset.Unspecified<br><br><br>// INT<br>fun Density.intPxToDp(px: Int) = px.toDp()<br><br>fun Density.intPxToSp(px: Int) = px.toSp()<br><br>@Composable<br>fun Int.toDp() = LocalDensity.current.intPxToDp(this)<br><br>@Composable<br>fun Int.toSp() = LocalDensity.current.intPxToSp(this)<br><br>fun Int.toFloatPx() = toFloat()<br><br>fun Int.toRecIntSize() = IntSize(this, this)<br><br>fun Int.toRecIntOffset() = IntOffset(this, this)<br><br><br>// DP SIZE<br>fun Density.dpSizeToIntSize(dpSize: DpSize) =<br>    if (dpSize.isSpecified) IntSize(dpSize.width.toPx().toInt(), dpSize.height.toPx().toInt())<br>    else IntSize.Zero<br><br>fun Density.dpSizeRoundToIntSize(dpSize: DpSize) =<br>    if (dpSize.isSpecified) IntSize(dpSize.width.roundToPx(), dpSize.height.roundToPx())<br>    else IntSize.Zero<br><br>fun Density.dpSizeToSize(dpSize: DpSize) =<br>    if (dpSize.isSpecified) Size(dpSize.width.toPx(), dpSize.height.toPx())<br>    else Size.Unspecified<br><br>@Composable<br>fun DpSize.toIntSize() = LocalDensity.current.dpSizeToIntSize(this)<br><br>@Composable<br>fun DpSize.roundToIntSize() = LocalDensity.current.dpSizeRoundToIntSize(this)<br><br>@Composable<br>fun DpSize.toSize() = LocalDensity.current.dpSizeToSize(this)<br><br>fun DpSize.isSpaced() = isSpecified &amp;&amp; width &gt; 0.dp &amp;&amp; height &gt; 0.dp<br><br><br>// SIZE<br>fun Density.sizeToDpSize(size: Size) =<br>    if (size.isSpecified) DpSize(size.width.toDp(), size.height.toDp())<br>    else DpSize.Unspecified<br><br>@Composable<br>fun Size.toDpSize() =<br>    if (isSpecified) LocalDensity.current.sizeToDpSize(this)<br>    else DpSize.Unspecified<br><br>fun Size.toIntSize() =<br>    if (isSpecified) IntSize(width.toInt(), height.toInt())<br>    else IntSize.Zero<br><br>fun Size.isSpaced() = isSpecified &amp;&amp; width &gt; 0F &amp;&amp; height &gt; 0F<br><br><br>// INT SIZE<br>fun Density.intSizeToDpSize(intSize: IntSize) = DpSize(intSize.width.toDp(), intSize.height.toDp())<br><br>@Composable<br>fun IntSize.toDpSize() = LocalDensity.current.intSizeToDpSize(this)<br><br>@Composable<br>fun IntSize.toSize() = Size(width.toFloat(), height.toFloat())<br><br>fun IntSize.isSpaced() = width &gt; 0 &amp;&amp; height &gt; 0<br><br><br>// DP OFFSET<br>fun Density.dpOffsetToIntOffset(dpOffset: DpOffset) =<br>    if (dpOffset.isSpecified) IntOffset(dpOffset.x.toPx().toInt(), dpOffset.y.toPx().toInt())<br>    else IntOffset.Zero<br><br>fun Density.dpOffsetRoundToIntOffset(dpOffset: DpOffset) =<br>    if (dpOffset.isSpecified) IntOffset(dpOffset.x.roundToPx(), dpOffset.y.roundToPx())<br>    else IntOffset.Zero<br><br>fun Density.dpOffsetToOffset(dpOffset: DpOffset) =<br>    if (dpOffset.isSpecified) Offset(dpOffset.x.toPx(), dpOffset.y.toPx())<br>    else Offset.Unspecified<br><br>@Composable<br>fun DpOffset.toIntOffset() = LocalDensity.current.dpOffsetToIntOffset(this)<br><br>@Composable<br>fun DpOffset.roundToIntOffset() = LocalDensity.current.dpOffsetRoundToIntOffset(this)<br><br>@Composable<br>fun DpOffset.toOffset() = LocalDensity.current.dpOffsetToOffset(this)<br><br><br>// OFFSET<br>fun Density.offsetToDpOffset(offset: Offset) =<br>    if (offset.isSpecified) DpOffset(offset.x.toDp(), offset.y.toDp())<br>    else DpOffset.Unspecified<br><br>@Composable<br>fun Offset.toDpOffset() = LocalDensity.current.offsetToDpOffset(this)<br><br>fun Offset.toIntOffset() =<br>    if (isSpecified) IntOffset(x.toInt(), y.toInt())<br>    else IntOffset.Zero<br><br>// INT OFFSET<br>fun Density.intOffsetToDpOffset(intOffset: IntOffset) = DpOffset(intOffset.x.toDp(), intOffset.y.toDp())<br><br>@Composable<br>fun IntOffset.toDpOffset() = LocalDensity.current.intOffsetToDpOffset(this)<br><br>fun IntOffset.toOffset() = Offset(x.toFloat(), y.toFloat())</pre><p><em>AutoSizeTextTest.kt: (optional — For test purpose)</em></p><pre>package com.inidamleader.ovtracker.util.compose<br><br>import androidx.compose.ui.unit.TextUnit<br>import androidx.compose.ui.unit.em<br>import androidx.compose.ui.unit.sp<br>import com.inidamleader.ovtracker.util.compose.SuggestedFontSizesStatus.Companion.suggestedFontSizesStatus<br>import org.junit.Test<br>import kotlin.test.assertEquals<br>import kotlin.test.assertFails<br>import kotlin.test.assertTrue<br><br>class AutoSizeTextTest {<br>    @Test<br>    fun findElectedIndexThrowException() {<br>        List(size = 0) { it }.run {<br>            assertFails { findElectedValue { false } }<br>        }<br>        List(size = 0) { it }.run {<br>            assertFails { findElectedValue { true } }<br>        }<br>    }<br><br>    @Test<br>    fun findElectedValueAt0() {<br>        List(size = 1) { it }.run {<br>            assertEquals(<br>                expected = 0,<br>                actual = findElectedValue { false },<br>            )<br>        }<br><br>        List(size = 1) { it }.run {<br>            assertEquals(<br>                expected = 0,<br>                actual = findElectedValue { true },<br>            )<br>        }<br><br>        List(size = 2) { it }.run {<br>            assertEquals(<br>                expected = 0,<br>                actual = findElectedValue { true },<br>            )<br>        }<br><br>        List(size = 15) { it }.run {<br>            assertEquals(<br>                expected = 0,<br>                actual = findElectedValue { true },<br>            )<br>        }<br><br>        List(size = 16) { it }.run {<br>            assertEquals(<br>                expected = 0,<br>                actual = findElectedValue { true },<br>            )<br>        }<br>    }<br><br>    @Test<br>    fun findElectedValueAt1() {<br>        List(size = 2) { it }.run {<br>            assertEquals(<br>                expected = 1,<br>                actual = findElectedValue { false },<br>            )<br>        }<br><br>        List(size = 2) { it }.run {<br>            assertEquals(<br>                expected = 1,<br>                actual = findElectedValue { it &gt; 1 },<br>            )<br>        }<br><br>        List(size = 15) { it }.run {<br>            assertEquals(<br>                expected = 1,<br>                actual = findElectedValue { it &gt; 1 },<br>            )<br>        }<br><br>        List(size = 16) { it }.run {<br>            assertEquals(<br>                expected = 1,<br>                actual = findElectedValue { it &gt; 1 },<br>            )<br>        }<br>    }<br><br>    @Test<br>    fun findElectedValueAt2() {<br>        List(size = 3) { it }.run {<br>            assertEquals(<br>                expected = 2,<br>                actual = findElectedValue { false },<br>            )<br>        }<br><br>        List(size = 14) { it }.run {<br>            assertEquals(<br>                expected = 2,<br>                actual = findElectedValue { it &gt; 2 },<br>            )<br>        }<br><br>        List(size = 15) { it }.run {<br>            assertEquals(<br>                expected = 2,<br>                actual = findElectedValue { it &gt; 2 },<br>            )<br>        }<br><br>        List(size = 16) { it }.run {<br>            assertEquals(<br>                expected = 2,<br>                actual = findElectedValue { it &gt; 2 },<br>            )<br>        }<br>    }<br><br>    @Test<br>    fun findElectedValueAt9() {<br>        List(size = 10) { it }.run {<br>            assertEquals(<br>                expected = 9,<br>                actual = findElectedValue { false },<br>            )<br>        }<br><br>        List(size = 14) { it }.run {<br>            assertEquals(<br>                expected = 9,<br>                actual = findElectedValue { it &gt; 9 },<br>            )<br>        }<br><br>        List(size = 15) { it }.run {<br>            assertEquals(<br>                expected = 9,<br>                actual = findElectedValue { it &gt; 9 },<br>            )<br>        }<br><br>        List(size = 16) { it }.run {<br>            assertEquals(<br>                expected = 9,<br>                actual = findElectedValue { it &gt; 9 },<br>            )<br>        }<br>    }<br><br>    @Test<br>    fun findElectedValueAt10() {<br>        List(size = 11) { it }.run {<br>            assertEquals(<br>                expected = 10,<br>                actual = findElectedValue { false },<br>            )<br>        }<br><br>        List(size = 14) { it }.run {<br>            assertEquals(<br>                expected = 10,<br>                actual = findElectedValue { it &gt; 10 },<br>            )<br>        }<br><br>        List(size = 15) { it }.run {<br>            assertEquals(<br>                expected = 10,<br>                actual = findElectedValue { it &gt; 10 },<br>            )<br>        }<br><br>        List(size = 16) { it }.run {<br>            assertEquals(<br>                expected = 10,<br>                actual = findElectedValue { it &gt; 10 },<br>            )<br>        }<br>    }<br><br>    @Test<br>    fun suggestedFontSizesStatus() {<br>        assertTrue {<br>            listOf(1.sp, 2.sp, 4.sp, 8.sp).suggestedFontSizesStatus == SuggestedFontSizesStatus.VALID<br>        }<br><br>        assertTrue {<br>            listOf(2.sp, 8.sp, 1.sp, 4.sp).suggestedFontSizesStatus == SuggestedFontSizesStatus.INVALID<br>        }<br><br>        assertTrue {<br>            emptyList&lt;TextUnit&gt;().suggestedFontSizesStatus == SuggestedFontSizesStatus.INVALID<br>        }<br><br>        assertTrue {<br>            listOf(1.sp, 2.em, 8.sp, 4.sp).suggestedFontSizesStatus == SuggestedFontSizesStatus.INVALID<br>        }<br>    }<br>}</pre><h3>Practical Implementation:</h3><p>Consider integrating AutoSizeText in scenarios where:</p><ul><li>You need to <strong>display variable-length text</strong> that must fit within constrained layouts without overflowing or being truncated.</li><li>You want to <strong>maintain consistent readability</strong> across a wide range of screen sizes, densities, and resolutions.</li><li>You’re aiming for a <strong>fluid, responsive UI</strong> where text adapts gracefully to its container without manual font size adjustments.</li></ul><h3>Conclusion:</h3><p><strong>Automatic text resizing is essential for building responsive and user-friendly mobile interfaces.</strong> While Jetpack Compose’s new autoSize feature is a great addition, it still has some limitations — particularly with multiline text and fine control over layout behavior.</p><p>That’s where AutoSizeText comes in. This custom composable not only offers greater precision and flexibility, but it’s also <strong>performance-friendly</strong> thanks to its use of a <strong>pseudo binary search algorithm</strong> to efficiently determine the optimal font size. This approach minimizes layout passes and ensures smooth rendering even in complex UIs.</p><p>By integrating AutoSizeText into your Compose projects, you can deliver a more polished and readable experience — without sacrificing performance or design integrity.</p><p>For detailed code examples and further exploration, find the complete source code on <a href="https://gist.github.com/inidamleader/b594d35362ebcf3cedf81055df519300">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b1c803eb7be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>