Skip to content

Conversation

@liangxianshen
Copy link

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant