完整示例参考如下:
import { MeasureUtils } from '@kit.ArkUI';
@Entry
@Component
struct MeasurePx2vpDemo {
textTitle: string = '发货订单';
textNumber: string = '123';
uiContext: UIContext = this.getUIContext();
uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils();
// 获取主体内容单行布局的长度
@State titleSize: SizeOptions = this.uiContextMeasure.measureTextSize({
textContent: this.textTitle,
fontSize: '30vp'
});
// 获取数字角标单行布局的长度
@State numberSize: SizeOptions = this.uiContextMeasure.measureTextSize({
textContent: this.textNumber,
fontSize: '15vp'
});
build() {
Column() {
RelativeContainer() {
// 主体内容
Row() {
Text(this.textTitle).fontSize('30vp');
}.id('row1');
// 数字角标
Row() {
Text(this.textNumber).fontSize('15vp').textAlign(TextAlign.Start).maxLines(1);
}.id('row2')
// alignRules属性将组件的顶部和右侧对齐
.alignRules({
top: { anchor: '__container__', align: VerticalAlign.Top },
right: { anchor: '__container__', align: HorizontalAlign.End }
})
// 通过offset属性将数字文本偏移
.offset({
x: this.getUIContext().px2vp(this.numberSize.width as number),
y: 0
});
}
.width(this.getUIContext().px2vp(this.titleSize.width as number))
.height(this.getUIContext().px2vp(this.titleSize.height as number));
}.width('100%').height('100%')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center);
}
} 效果如下:
