API 参考
以下为常用 API 的精简说明,完整行为以包内类型定义与官方文档为准。
用例一:只关心高度
import { prepare, layout } from '@chenglou/pretext'
const prepared = prepare('你好世界', '16px Inter')
const { height, lineCount } = layout(prepared, 280, 24)- prepare(text, font, options?):font 与 CanvasRenderingContext2D.font 格式一致;可选 { whiteSpace: 'pre-wrap' }。
- layout(prepared, maxWidth, lineHeight):返回高度与行数。
用例二:需要每行文本或变宽断行
import {
prepareWithSegments,
layoutWithLines,
walkLineRanges,
layoutNextLine,
} from '@chenglou/pretext'
const p = prepareWithSegments(text, font)
const { lines, height, lineCount } = layoutWithLines(p, maxWidth, lineHeight)
walkLineRanges(p, maxWidth, (line) => {
// line.width, line.start, line.end
})
let cursor = { segmentIndex: 0, graphemeIndex: 0 }
for (;;) {
const line = layoutNextLine(p, cursor, widthForThisLine)
if (line === null) break
cursor = line.end
}主要类型(概念)
- LayoutLine:text、width、start、end。
- LayoutCursor:segmentIndex、graphemeIndex。
其他
- clearCache():清空内部测量缓存(例如频繁切换字体时)。
- setLocale(locale?):影响后续 prepare 的区域设置并会清空缓存。
- profilePrepare(...):性能剖析用。