Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Android] Fix: incorrect line-height calculation #17952

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,12 @@ public void chooseHeight(
// Show proportionally additional ascent / top & descent / bottom
final int additional = mHeight - (-fm.top + fm.bottom);

fm.top -= additional / 2;
fm.ascent -= additional / 2;
fm.descent += additional / 2;
fm.bottom += additional / 2;
// Round up for the negative values and down for the positive values (arbritary choice)
// So that bottom - top equals additional even if it's an odd number.
fm.top -= Math.ceil(additional / 2.0f);
fm.bottom += Math.floor(additional / 2.0f);
fm.ascent = fm.top;
fm.descent = fm.bottom;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,35 @@
public class CustomLineHeightSpanTest {

@Test
public void shouldIncreaseAllMetricsProportionally() {
public void evenLineHeightShouldIncreaseAllMetricsProportionally() {
CustomLineHeightSpan customLineHeightSpan = new CustomLineHeightSpan(22);
Paint.FontMetricsInt fm = new Paint.FontMetricsInt();
fm.top = -10;
fm.ascent = -5;
fm.descent = 5;
fm.bottom = 10;
customLineHeightSpan.chooseHeight("Hi", 0, 2, 0, 0, fm);
// Since line height is even it should be equally added to top and bottom.
assertThat(fm.top).isEqualTo(-11);
assertThat(fm.ascent).isEqualTo(-6);
assertThat(fm.descent).isEqualTo(6);
assertThat(fm.ascent).isEqualTo(-11);
assertThat(fm.descent).isEqualTo(11);
assertThat(fm.bottom).isEqualTo(11);
assertThat(fm.bottom - fm.top).isEqualTo(22);
}

@Test
public void oddLineHeightShouldAlsoWork() {
CustomLineHeightSpan customLineHeightSpan = new CustomLineHeightSpan(23);
Paint.FontMetricsInt fm = new Paint.FontMetricsInt();
fm.top = -10;
fm.ascent = -5;
fm.descent = 5;
fm.bottom = 10;
customLineHeightSpan.chooseHeight("Hi", 0, 2, 0, 0, fm);
// Only test that the sum is correct so the implementation
// is free to add the odd value either on top or bottom.
assertThat(fm.descent - fm.ascent).isEqualTo(23);
assertThat(fm.bottom - fm.top).isEqualTo(23);
}

@Test
Expand Down