Skip to content

Commit 6b9afd8

Browse files
authored
Keep adjustsFontSizeToFit from shrinking text at whole-pixel heights on Android
Summary: `adjustsFontSizeToFit` shrinks the font while the text layout is taller than its `AT_MOST` height. That height arrives in pixels after Yoga subtracts the container's padding and converts it from DIPs back to pixels, all in 32-bit floats, so a whole number of pixels can come back a fraction short: 46px comes back as 45.999996px. A layout exactly as tall as the space it was given then counts as too tall. When the text sets a `lineHeight`, shrinking the font never makes it shorter, so it shrinks all the way to the minimum font size. Compare the layout height against the `AT_MOST` height with the same 0.001px tolerance the previous change added for widths, now named `PIXEL_SIZE_TOLERANCE`. Adds a unit test and an RNTester example. The example lays out 17 labels, each with a `lineHeight` of a whole number of pixels, in containers that leave exactly that height below their padding. Each row is a pixel taller than the last. Without this change, 11 of them shrink to the minimum font size at 320dpi and 4 at 420dpi. Changelog: [Android][Fixed] - Fix `adjustsFontSizeToFit` shrinking text that exactly fits its container's height Differential Revision: D129533186 Pull Request resolved: #59792
1 parent ab9f00d commit 6b9afd8

3 files changed

Lines changed: 161 additions & 5 deletions

File tree

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/text/TextLayoutManager.kt‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,9 @@ internal object TextLayoutManager {
118118

119119
private const val TEXT_WIDTH_MODE_LONGEST_LINE = "longest-line"
120120

121-
// Widths arrive in pixels converted from Yoga's floating point DIPs, so a width of a whole number
122-
// of pixels can arrive a fraction of a pixel short of it (e.g. 371.99997 instead of 372).
123-
private const val PIXEL_WIDTH_TOLERANCE = 0.001f
121+
// Sizes arrive in pixels converted from Yoga's floating point DIPs, so a whole number of pixels
122+
// can arrive a fraction of a pixel short of it (e.g. 371.99997 instead of 372).
123+
private const val PIXEL_SIZE_TOLERANCE = 0.001f
124124

125125
private val tagToSpannableCache = ConcurrentHashMap<Int, Spannable>()
126126

@@ -982,7 +982,7 @@ internal object TextLayoutManager {
982982
* width back as its constraint once Yoga has converted it to DIPs and back, and flooring that to
983983
* one pixel less wraps the text.
984984
*/
985-
private fun floorPixelWidth(width: Float): Int = floor(width + PIXEL_WIDTH_TOLERANCE).toInt()
985+
private fun floorPixelWidth(width: Float): Int = floor(width + PIXEL_SIZE_TOLERANCE).toInt()
986986

987987
@VisibleForTesting
988988
internal fun adjustLayoutForRtlRightOverhang(
@@ -1560,7 +1560,8 @@ internal object TextLayoutManager {
15601560

15611561
val singleLineTextExceedsWidth = text.length == 1 && layout.getLineWidth(0) > width
15621562
val exceedsHeight =
1563-
heightYogaMeasureMode != YogaMeasureMode.UNDEFINED && layout.height > height
1563+
heightYogaMeasureMode != YogaMeasureMode.UNDEFINED &&
1564+
layout.height > height + PIXEL_SIZE_TOLERANCE
15641565
val exceedsMaximumNumberOfLines =
15651566
maximumNumberOfLines != ReactConstants.UNSET &&
15661567
maximumNumberOfLines != 0 &&
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/*
2+
* Copyright (c) Meta Platforms, Inc. and affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
package com.facebook.react.views.text
9+
10+
import android.annotation.SuppressLint
11+
import android.graphics.text.LineBreakConfig
12+
import android.text.Layout
13+
import android.text.SpannableString
14+
import android.text.Spanned
15+
import android.text.StaticLayout
16+
import android.text.TextPaint
17+
import com.facebook.react.common.ReactConstants
18+
import com.facebook.react.uimanager.DisplayMetricsHolder
19+
import com.facebook.react.views.text.internal.span.ReactAbsoluteSizeSpan
20+
import com.facebook.yoga.YogaMeasureMode
21+
import org.assertj.core.api.Assertions.assertThat
22+
import org.junit.After
23+
import org.junit.Before
24+
import org.junit.Test
25+
import org.junit.runner.RunWith
26+
import org.robolectric.RobolectricTestRunner
27+
import org.robolectric.RuntimeEnvironment
28+
import org.robolectric.annotation.GraphicsMode
29+
import org.robolectric.annotation.TextLayoutMode
30+
31+
@RunWith(RobolectricTestRunner::class)
32+
@GraphicsMode(GraphicsMode.Mode.NATIVE)
33+
@TextLayoutMode(TextLayoutMode.Mode.REALISTIC)
34+
@SuppressLint("InlinedApi")
35+
class TextLayoutManagerFontSizeToFitPixelHeightTest {
36+
37+
@Before
38+
fun setUp() {
39+
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(RuntimeEnvironment.getApplication())
40+
}
41+
42+
@After
43+
fun tearDown() {
44+
DisplayMetricsHolder.setScreenDisplayMetrics(null)
45+
}
46+
47+
@Test
48+
fun `AT_MOST height a floating point error short of the text height keeps the font size`() {
49+
val textHeight = layoutHeight(spannableWithFontSize(FONT_SIZE))
50+
51+
for (height in listOf(Math.nextDown(textHeight.toFloat()), textHeight - 0.0004f)) {
52+
val text = spannableWithFontSize(FONT_SIZE)
53+
adjustToFitHeight(text, height)
54+
55+
assertThat(fontSize(text)).isEqualTo(FONT_SIZE)
56+
}
57+
}
58+
59+
@Test
60+
fun `AT_MOST height a fraction of a pixel short of the text height shrinks the font`() {
61+
val text = spannableWithFontSize(FONT_SIZE)
62+
adjustToFitHeight(text, layoutHeight(text) - 0.5f)
63+
64+
assertThat(fontSize(text)).isLessThan(FONT_SIZE)
65+
}
66+
67+
private fun spannableWithFontSize(fontSize: Int): SpannableString =
68+
SpannableString("Add payment method").apply {
69+
setSpan(ReactAbsoluteSizeSpan(fontSize), 0, length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
70+
}
71+
72+
private fun paint(): TextPaint =
73+
TextPaint(TextPaint.ANTI_ALIAS_FLAG).apply { textSize = FONT_SIZE.toFloat() }
74+
75+
private fun layoutHeight(text: SpannableString): Int =
76+
StaticLayout.Builder.obtain(text, 0, text.length, paint(), WIDTH.toInt())
77+
.setIncludePad(false)
78+
.build()
79+
.height
80+
81+
private fun fontSize(text: SpannableString): Int =
82+
text.getSpans(0, text.length, ReactAbsoluteSizeSpan::class.java).single().size
83+
84+
private fun adjustToFitHeight(text: SpannableString, height: Float) {
85+
TextLayoutManager.adjustSpannableFontToFit(
86+
text,
87+
WIDTH,
88+
YogaMeasureMode.EXACTLY,
89+
height,
90+
YogaMeasureMode.AT_MOST,
91+
/* minimumFontSizeAttr = */ Float.NaN,
92+
/* minimumFontScale = */ Float.NaN,
93+
ReactConstants.UNSET,
94+
/* includeFontPadding = */ false,
95+
Layout.BREAK_STRATEGY_HIGH_QUALITY,
96+
Layout.HYPHENATION_FREQUENCY_NONE,
97+
LineBreakConfig.LINE_BREAK_STYLE_NONE,
98+
LineBreakConfig.LINE_BREAK_WORD_STYLE_NONE,
99+
Layout.Alignment.ALIGN_NORMAL,
100+
/* justificationMode = */ 0,
101+
paint(),
102+
)
103+
}
104+
105+
private companion object {
106+
const val FONT_SIZE = 40
107+
const val WIDTH = 1000f
108+
}
109+
}

‎packages/rn-tester/js/examples/Text/TextExample.android.js‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1415,6 +1415,39 @@ function FitContentWholePixelWidthExample(props: {}): React.Node {
14151415
return <View testID="text-fit-content-whole-pixel-width">{rows}</View>;
14161416
}
14171417

1418+
function AdjustsFontSizeToFitWholePixelHeightExample(props: {}): React.Node {
1419+
// Each label's line height is a whole number of pixels, and so is the space
1420+
// its container leaves for it below the container's padding. That space
1421+
// picks up floating point error from the padding and from the conversion to
1422+
// DIPs and back, so it can fall a hair short of the line height. Each row is
1423+
// a pixel taller than the last. No label should shrink.
1424+
const pixelRatio = PixelRatio.get();
1425+
const rows = [];
1426+
for (let i = 0; i < 17; i++) {
1427+
const lineHeight = (Math.round(20 * pixelRatio) + i) / pixelRatio;
1428+
rows.push(
1429+
<View
1430+
key={i}
1431+
style={[
1432+
styles.adjustsFontSizeToFitRow,
1433+
{height: lineHeight + styles.adjustsFontSizeToFitRow.paddingTop},
1434+
]}>
1435+
<Text
1436+
adjustsFontSizeToFit={true}
1437+
numberOfLines={1}
1438+
style={[styles.adjustsFontSizeToFitLabel, {lineHeight}]}>
1439+
Add payment method
1440+
</Text>
1441+
</View>,
1442+
);
1443+
}
1444+
return (
1445+
<View testID="text-adjusts-font-size-to-fit-whole-pixel-height">
1446+
{rows}
1447+
</View>
1448+
);
1449+
}
1450+
14181451
const examples = [
14191452
{
14201453
title: 'Wrapped text width mode',
@@ -1516,6 +1549,11 @@ const examples = [
15161549
name: 'fitContentWholePixelWidth',
15171550
render: FitContentWholePixelWidthExample,
15181551
},
1552+
{
1553+
title: 'adjustsFontSizeToFit at whole pixel heights',
1554+
name: 'adjustsFontSizeToFitWholePixelHeight',
1555+
render: AdjustsFontSizeToFitWholePixelHeightExample,
1556+
},
15191557
{
15201558
title: 'Hyphenation',
15211559
name: 'hyphenation',
@@ -2035,6 +2073,14 @@ const styles = StyleSheet.create({
20352073
fontSize: 15,
20362074
maxWidth: '100%',
20372075
},
2076+
adjustsFontSizeToFitRow: {
2077+
backgroundColor: '#E4E6EB',
2078+
marginBottom: 2,
2079+
paddingTop: 7.1,
2080+
},
2081+
adjustsFontSizeToFitLabel: {
2082+
fontSize: 16,
2083+
},
20382084
lineBreakSample: {
20392085
backgroundColor: '#eee',
20402086
fontSize: 16,

0 commit comments

Comments
 (0)