Rich text labels

This commit is contained in:
Andreas Hocevar
2022-02-21 23:25:33 +01:00
parent 1f8338d3b8
commit 18f06b8b9a
10 changed files with 313 additions and 48 deletions

View File

@@ -367,21 +367,36 @@ export function measureAndCacheTextWidth(font, text, cache) {
}
/**
* @param {string} font Font to use for measuring.
* @param {Array<string>} lines Lines to measure.
* @param {Array<number>} widths Array will be populated with the widths of
* each line.
* @return {number} Width of the whole text.
* @param {TextState} baseStyle Base style.
* @param {Array<string>} chunks Text chunks to measure.
* @return {{width: number, height: number, widths: Array<number>, heights: Array<number>, lineWidths: Array<number>}}} Text metrics.
*/
export function measureTextWidths(font, lines, widths) {
const numLines = lines.length;
export function getTextDimensions(baseStyle, chunks) {
const widths = [];
const heights = [];
const lineWidths = [];
let width = 0;
for (let i = 0; i < numLines; ++i) {
const currentWidth = measureTextWidth(font, lines[i]);
width = Math.max(width, currentWidth);
let lineWidth = 0;
let height = 0;
let lineHeight = 0;
for (let i = 0, ii = chunks.length; i <= ii; i += 2) {
const text = chunks[i];
if (text === '\n' || i === ii) {
width = Math.max(width, lineWidth);
lineWidths.push(lineWidth);
lineWidth = 0;
height += lineHeight;
continue;
}
const font = chunks[i + 1] || baseStyle.font;
const currentWidth = measureTextWidth(font, text);
widths.push(currentWidth);
lineWidth += currentWidth;
const currentHeight = measureTextHeight(font);
heights.push(currentHeight);
lineHeight = Math.max(lineHeight, currentHeight);
}
return width;
return {width, height, widths, heights, lineWidths};
}
/**