
鸿蒙通用属性-位置设置position、offset对比 原创
修改一个组件的位置,可以通过position或offset实现,今天通过一篇文章,了解这两个属性的异同。
相同点
传参类型:他们都支持三个传参类型,分别是Position、Edges、LocalizedEdges,接下来详细看一每个类型。
Position:用于表示一个坐标点,参数可选。
名称 | 说明 |
---|---|
x | x轴坐标。单位:vp |
y | y轴坐标。单位:vp |
Edges:表示相对四边的偏移量。同时设置top和bottom,仅top生效;同时设置left和right,仅left生效。参数可选。参数类型为Dimension类型,稍后介绍
名称 | 说明 |
---|---|
top | 相对顶边的偏移量。 |
bottom | 相对底边的偏移量。 |
left | 相对左边的偏移量。 |
right | 相对右边的偏移量。 |
LocalizedEdges:表示相对四边的偏移量。同时设置top和bottom,仅top生效;同时设置start和end,仅start生效。参数可选。参数类型为LengthMetrics类型,稍后介绍
名称 | 说明 |
---|---|
top | 相对顶边的偏移量。 |
bottom | 相对底边的偏移量。 |
start | LTR模式时相对左边的偏移量,RTL模式时相对右边的偏移量。 |
end | LTR模式时相对右边的偏移量,RTL模式时相对左边的偏移量。 |
以上是三个传参类型的属性介绍,接下来看一下Dimension和LengthMetrics,他们的传值类型更多样
Dimension
名称 | 说明 |
---|---|
PX | 以px像素单位,如’10px’。 |
VP | 以数字或vp像素单位,如10或’10vp’。 |
FP | 以fp像素单位,如’10fp’。 |
LPX | 以lpx像素单位,如’10lpx’。 |
Percentage | 以%像素单位,如’10%'。 |
Resource | 引入系统资源。 |
LengthMetrics 需要传2个参数,为必传
名称 | 说明 |
---|---|
value | 长度属性的值。 |
unit | 长度属性的单位,默认为VP。(PX、VP、FP、Percentage) |
不同点
1.offset和position一起使用时,position生效,offset不生效。
2.offset是相对于自己的初始位置进行偏移,position是相对于父容器偏移
3.当父容器是Row/Column/Flex时,设置position的子组件不占位。
Row(){
Row().backgroundColor(Color.Yellow).width(100).height(100).onAreaChange((oldValue: Area, newValue: Area)=>{
this.areaWidth=newValue.width as number
this.areaHeight=newValue.height as number
this.positionX=newValue.position.x as number
this.positionY=newValue.position.y as number
this.globalX=newValue.globalPosition.x as number
this.globalY=newValue.globalPosition.y as number
})
.position({
x:this.positionX,
y:this.positionY
})
// .offset({
// x:this.offsetX
// })
Row().backgroundColor(Color.Red).width(30).height(100)
Row().backgroundColor(Color.Blue).width(30).height(100)
Row().backgroundColor(Color.Green).width(30).height(100)
}
.justifyContent(FlexAlign.SpaceAround)
4.当父容器为RelativeContainer时,子组件设置了alignRules属性时,子组件的position属性不生效。当子组件没有设置alignRules,绘制完成之后,修改position和offset,不影响其他子组件的位置。
RelativeContainer(){
Row().backgroundColor(Color.Yellow).width(100).height(100).onAreaChange((oldValue: Area, newValue: Area)=>{
this.areaWidth=newValue.width as number
this.areaHeight=newValue.height as number
this.positionX=newValue.position.x as number
this.positionY=newValue.position.y as number
this.globalX=newValue.globalPosition.x as number
this.globalY=newValue.globalPosition.y as number
})
.position({
x:this.positionX,
y:this.positionY
})
.id('row1')
// .offset({
// x:this.offsetX
// })
Row().backgroundColor(Color.Blue).width(30).height(100).alignRules(AlignRules.right('row1'))
}
5.动态修改position时,会触发组件的onAreaChange回调,修改offset时,不会触发
