通过转换公式计算,毫米值=(像素值×25.4) / DPI。示例代码如下:
// mm转px函数
function mmToPx(mmValue: number, isYaxis: boolean) {
let displayInfo = display.getDefaultDisplaySync();
if (isYaxis) {
return (mmValue / 25.4) * displayInfo.yDPI; // 应用标准公式
} else {
return (mmValue / 25.4) * displayInfo.xDPI; // 应用标准公式
}
} 实际应用场景:在线测量工具尺子,完整示例代码如下:
import { display, window } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
// 直尺线类
class RulerLineInfo {
index: number;
height: number;
mmPx: number; // 1毫米对应的像素值
textWidth: number; // 刻度文字宽度
textHeight: number; // 刻度文字高度
constructor(index: number, height: number, mmPx: number) {
this.index = index;
this.height = height;
this.mmPx = mmPx;
this.textWidth = mmPx * 2 * (((index / 10) > 9 ? 2 : 1));
this.textHeight = mmPx * 4;
}
showNumber(): string {
return this.index % 10 === 0 ? `${Math.floor(this.index / 10)}` : '';
}
}
// mm转px函数
function mmToPx(mmValue: number, isYaxis: boolean) {
let displayInfo = display.getDefaultDisplaySync();
if (isYaxis) {
return (mmValue / 25.4) * displayInfo.yDPI; // 应用标准公式
} else {
return (mmValue / 25.4) * displayInfo.xDPI; // 应用标准公式
}
}
@Entry
@Component
struct RulerComponent {
@State rulerLines: RulerLineInfo[] = [];
aboutToAppear(): void {
let mmPx = mmToPx(1, true);
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
window.getLastWindow(context).then((windowClass) => {
windowClass.setPreferredOrientation(window.Orientation.LANDSCAPE);
});
// 初始化直尺线类
for (let i = 0; i <= 10 * 10; i++) {
let lineHeight: number = (i % 10 === 0) ? 90 : (i % 5 === 0) ? 60 : 45;
this.rulerLines.push(new RulerLineInfo(i, lineHeight, mmPx));
}
}
build() {
Column() {
Row() {
ForEach(this.rulerLines, (line: RulerLineInfo, index: number) => {
// 生成直线
Line()
.width(0.5)
.height(`${line.height}px`)
.backgroundColor(Color.Black)
.stroke(Color.Black)
.position({ x: `${line.mmPx * index}px`, y: 0 })
// 生成数字
Text(line.showNumber())
.fontColor(Color.Black)
.fontSize(18)
.width(`${line.textWidth}px`)
.height(`${line.textHeight}px`)
.textAlign(TextAlign.Center)
.position({
x: `${line.mmPx * index - line.textWidth / 2}px`,
y: `${line.height}px`
})
});
}
.width('100%')
.height('30%')
.margin({ left: 150 })
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
}
}