fix:Y coordinate calculation error when addText on Android #155
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The problem comes from an incorrect calculation method for the y-coordinate and row height - you moved the canvas (canvas. translate (text. x, text. y)),
But later, when calculating the y of each row, text. y was added, resulting in the vertical offset being calculated repeatedly;
Also, using (i+1) * fontSizePx as the line spacing is not accurate
(Ignoring the line to line calculation of the font's ascending/descending/reading/StatisticLayout),
And using text. x as the x-coordinate during left alignment will also result in repeated offsets (because the canvas has already been translated by x).
The recommended and more robust approach is to have Static Layout responsible for inter row and baseline calculations,
Then draw the entire layout onto the canvas (using canvas. save()/translate()/resto()),
This won't make any mistakes. The following is the corrected code (only modifying the implementation of drawText/getStatisticLayout):
Briefly explain why fixing can solve the problem:
No longer manually adding text. y (which previously caused duplicate offset) when calculating each row. After changing to canvas. translate (text. x, text. y),
Hand over the relative displacement of y to Static Layout for management.
Using StatisticLayout.draw (canvas) can correctly handle baseline, row height, line breaks, and alignment (avoiding bias in estimating row height using fontSizePx).
Using canvas. save()/store() is safer and semantically clearer than manually translating (revert).
Handled the situation where the available width is negative to avoid Static Layout receiving negative width.
If you do have special reasons to manually draw line by line (such as custom line spacing or highlighted text), the minimum fix is:
Do not add text. y in lineY (as it has already been translated).
Use the row baseline provided by StaticLayout or fontPaint.fontSpacing to calculate the y of rows (instead of (i+1) * fontSizePx).
When aligning to the left, lineX should be 0 (because x has already been translated).