Catch Overlapping Labels Before Rendering With a Sweep Over X
First published on Homingo Learn . A label that fits today can land on its neighbor tomorrow when someone renames a metric or adds a series, and you may not notice until the chart is on screen. You can flag likely collisions without rendering by estimating a box for each label and checking the boxes against each other. The technique Each label's box comes from arithmetic on its text: Width is…
First, each label's box is created by calculating its width and height based on its text and size. The width is determined by multiplying the length of the text by the size and a constant of 0.6, assuming an average character is 0.6 em wide. The height is calculated by multiplying the size by a constant of 1.2, assuming a line height of 1.2 em. These constants are approximations and the program does not verify them against the actual rendered text.
To identify overlapping labels, the labels are sorted by their left edge and processed sequentially. An active list keeps track of boxes that may still overlap with the current label being considered. For each new label, the active list is updated by removing boxes that end at or before the current label's left edge. The y range of the current label is then compared against each remaining box in the active list to check for overlaps. The number of comparisons made is also tracked.
If an overlap is detected, the overlapping pairs are added to a set of hits. After processing all labels, the set of hits and the total number of comparisons are returned. This method allows for efficient detection of overlapping label boxes without rendering the chart, but it relies on the assumptions made about character width and line height.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.