1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
export function getBoundingRect( text: string, font: string, textAlign?: TextAlign, textBaseline?: TextVerticalAlign ) { const textLines = ((text || '') + '').split('\n'); const len = textLines.length; if (len === 1) { return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline); } else { const uniondRect = new BoundingRect(0, 0, 0, 0); for (let i = 0; i < textLines.length; i++) { const rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline); i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect); } return uniondRect; } }
export function innerGetBoundingRect( text: string, font: string, textAlign?: TextAlign, textBaseline?: TextVerticalAlign ): BoundingRect { const width = getWidth(text, font); const height = getLineHeight(font);
const x = adjustTextX(0, width, textAlign); const y = adjustTextY(0, height, textBaseline);
const rect = new BoundingRect(x, y, width, height);
return rect; }
export function getWidth(text: string, font: string): number { font = font || DEFAULT_FONT; let cacheOfFont = textWidthCache[font]; if (!cacheOfFont) { cacheOfFont = textWidthCache[font] = new LRU(500); } let width = cacheOfFont.get(text); if (width == null) { width = platformApi.measureText(text, font).width; cacheOfFont.put(text, width); }
return width; }
export function getLineHeight(font?: string): number { return getWidth('国', font); }
export function adjustTextX(x: number, width: number, textAlign: TextAlign): number { if (textAlign === 'right') { x -= width; } else if (textAlign === 'center') { x -= width / 2; } return x; }
export function adjustTextY(y: number, height: number, verticalAlign: TextVerticalAlign): number { if (verticalAlign === 'middle') { y -= height / 2; } else if (verticalAlign === 'bottom') { y -= height; } return y; }
|