HarmonyOS Length类型的尺寸如何转换为数值进行计算?

我在自定义控件中 onMeasureSize 、onPlaceChildren 获取到的都是 Length 类型数据,我需要如何转为数值进行计算?

阅读 597
1 个回答

关于onPlaceChildren和onMeasureSize,可以参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-custom-component-layout-V5\#onplacechildren10

ArkUI框架会在自定义组件布局时,将该自定义组件的子节点自身的尺寸范围通过onPlaceChildren传递给该自定义组件。onPlaceChildren的返回值为空。

ArkUI框架会在自定义组件确定尺寸时,将该自定义组件的节点信息和尺寸范围通过onMeasureSize传递给该开发者。onMeasureSize方法的返回值为SizeResult(组件尺寸信息),是自定义的组件尺寸。

SizeResult的相关信息,

可以查看文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-custom-component-layout-V5\#sizeresult10

SizeResult内包含两种属性,width和height,他们的类型都是number,单位都是vp。

自定义布局代码示例,参考如下demo:

// xxx.ets
@Entry
@Component
struct Index {
  build() {
    Column() {
      CustomLayout({ builder: ColumnChildren })
    }
  }
}

@Builder
function ColumnChildren() {
  ForEach([1, 2, 3], (index: number) => { //暂不支持lazyForEach的写法
    Text('S' + index)
      .fontSize(30)
      .width(100)
      .height(100)
      .borderWidth(2)
      .offset({ x: 10, y: 20 })
  })
}
@Component
struct CustomLayout {
  @Builder
  doNothingBuilder() {
  };
  @BuilderParam builder: () => void = this.doNothingBuilder;
  @State startSize: number = 100;
  result: SizeResult = {
    width: 0,
    height: 0
  };
  onPlaceChildren(selfLayoutInfo: GeometryInfo, children: Array<Layoutable>, constraint: ConstraintSizeOptions) {
    let startPos = 300;
    children.forEach((child) => {
      let pos = startPos - child.measureResult.height;
      child.layout({ x: pos, y: pos })
    })
  }
  onMeasureSize(selfLayoutInfo: GeometryInfo, children: Array<Measurable>, constraint: ConstraintSizeOptions) {
    let size = 100;
    children.forEach((child) => {
      let result: MeasureResult = child.measure({ minHeight: size, minWidth: size, maxWidth: size, maxHeight: size })
      size += result.width / 2
      ;
    })
    this.result.width = 100;
    this.result.height = 400;
    return this.result;
  }
  build() {
    this.builder()
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进