onSizeChange是实际绘制的值,可以使用组件级像素取整pixelRound把组件的对齐方式设置为不取整计算。
@Component struct onAreaChangeSolution1 { aboutToAppear() { } build() { Column() { Column() { } .pixelRound({ start: PixelRoundCalcPolicy.NO_FORCE_ROUND, end: PixelRoundCalcPolicy.NO_FORCE_ROUND, top: PixelRoundCalcPolicy.NO_FORCE_ROUND, bottom: PixelRoundCalcPolicy.NO_FORCE_ROUND }) .height('2') .onSizeChange((_, area: SizeOptions) => { console.info('=====onSizeChange: ' + this.getUIContext().vp2px(area.height as number)); }) .onAreaChange((_, area: Area) => { console.info('=====onAreaChange: ' + this.getUIContext().vp2px(area.height as number)); }); Column() { } .pixelRound({ start: PixelRoundCalcPolicy.NO_FORCE_ROUND, end: PixelRoundCalcPolicy.NO_FORCE_ROUND, top: PixelRoundCalcPolicy.NO_FORCE_ROUND, bottom: PixelRoundCalcPolicy.NO_FORCE_ROUND }) .height('2') .onSizeChange((_, area: SizeOptions) => { console.info('=====onSizeChange2: ' + this.getUIContext().vp2px(area.height as number)); }) .onAreaChange((_, area: Area) => { console.info('=====onAreaChange2: ' + this.getUIContext().vp2px(area.height as number)); }); } .pixelRound({ start: PixelRoundCalcPolicy.NO_FORCE_ROUND, end: PixelRoundCalcPolicy.NO_FORCE_ROUND, top: PixelRoundCalcPolicy.NO_FORCE_ROUND, bottom: PixelRoundCalcPolicy.NO_FORCE_ROUND }) .backgroundColor(Color.Pink) .width('100%') .onSizeChange((_, area: SizeOptions) => { console.info('=====onSizeChange_out: ' + this.getUIContext().vp2px(area.height as number)); }) .onAreaChange((_, area: Area) => { console.info('=====onAreaChange_out: ' + this.getUIContext().vp2px(area.height as number)); }); } }
Q:如何使用onAreaChange对Row组件进行布局?
A:可以使用onAreaChange获取Row组件的宽度,进行布局。
@Component struct onAreaChangeSolution2 { @State widthAll: number = 0; @State widthA: number = 0; build() { Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) { Stack() { Row() { Text('标题'); Text('字符串字符串字符串字符串字符串字符串'); } .height(50) .backgroundColor('red') .id('A') .onAreaChange((oldValue: Area, newValue: Area) => { let info = JSON.stringify(newValue.width); this.widthA = parseFloat(info); }) .margin({ left: -1 }); Row() { Text('增长率70.5%'); } .height(50) .backgroundColor('blue') .width(this.widthAll - this.widthA) .id('B') .margin({ left: 281 }); }; } .width('100%') .onAreaChange((oldValue: Area, newValue: Area) => { let info = JSON.stringify(newValue.width); this.widthAll = parseFloat(info); console.log('=================>all:' + this.widthAll); }) .backgroundColor(Color.Green); } }