labelTemplateUnits.ts
1.21 KB
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
/**
* 标签模板设计坐标系(与 APP renderLabelPreviewCanvas.toCanvasPx、原生 DESIGN_DPI=96 一致)
* 1 cm = 37.8 px,1 inch = 96 px
*/
export const PX_PER_CM = 37.8;
export const PX_PER_INCH = 96;
export type LabelTemplateUnit = "cm" | "inch" | "mm" | "px";
export function unitToPx(value: number, unit: LabelTemplateUnit | string): number {
const v = Number(value) || 0;
const u = String(unit || "inch").toLowerCase();
if (u === "mm") return (v / 25.4) * PX_PER_INCH;
if (u === "cm") return v * PX_PER_CM;
if (u === "px") return v;
return v * PX_PER_INCH;
}
export function pxToUnit(px: number, unit: LabelTemplateUnit | string): number {
const u = String(unit || "inch").toLowerCase();
if (u === "mm") return (px * 25.4) / PX_PER_INCH;
if (u === "cm") return px / PX_PER_CM;
if (u === "px") return px;
return px / PX_PER_INCH;
}
/** 模板纸张在设计像素下的宽高(如 5cm → 189×189) */
export function templatePaperPx(
width: number,
height: number,
unit: LabelTemplateUnit | string,
): { widthPx: number; heightPx: number } {
return {
widthPx: Math.max(1, Math.round(unitToPx(width, unit))),
heightPx: Math.max(1, Math.round(unitToPx(height, unit))),
};
}