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

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

HarmonyOS
2024-12-24 18:11:11
582浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

关于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()
  }
}
  • 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.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
分享
微博
QQ
微信
回复
2024-12-24 19:46:46
相关问题
HarmonyOS Length 如何转换为具体数值
1153浏览 • 1回复 待解决
HarmonyOS 基础类型Length计算
711浏览 • 1回复 待解决
HarmonyOS Resource怎么进行转换类型
1407浏览 • 1回复 待解决
ReactNative项目如何转换为HarmonyOS框架
3468浏览 • 0回复 待解决
HarmonyOS 如何将视频转换为GIF
821浏览 • 1回复 待解决
HarmonyOS 请问如何把map转换为jsonstring
540浏览 • 1回复 待解决
HarmonyOS 时间戳如何转换为时间
668浏览 • 1回复 待解决
求告知HAR如何转换为HSP
1121浏览 • 1回复 待解决
HarmonyOS timestamp转换为正常时间戳
726浏览 • 1回复 待解决