Android ConstraintLayout layout_constraintDimensionRatio w h 备忘

注:以下结论由测试推测得到,仅仅是结果表现上合理,并非一定就是ConstraintLayout内部实现机制,不敢误导他人,仅自己记录备忘

ConstraintLayout layout_constraintDimensionRatio 可以设置一个前缀 w或h,

根据官方说法

The ratio can be expressed either as:

  • a float value, representing a ratio between width and height
  • a ratio in the form "width:height"

You can also use ratio if both dimensions are set to MATCH_CONSTRAINT (0dp). In this case the system sets the largest dimensions the satisfies all constraints and maintains the aspect ratio specified. To constrain one specific side based on the dimensions of another, you can pre append W," or H, to constrain the width or height respectively. For example, If one dimension is constrained by two targets (e.g. width is 0dp and centered on parent) you can indicate which side should be constrained, by adding the letter W (for constraining the width) or H (for constraining the height) in front of the ratio, separated by a comma:

 当一个子组件的宽和高都设置为0dp的时候,可以用前缀w或h指示,哪条边(w或h)通过Ratio计算得到其长度。Android会先通过其他约束条件计算另一条边的值,再通过Ratio  w:h=ratio 计算指定的边(w或h)的值。

例如:w=0dp,h=0dp,toLeftOf="parent",toRightOf="parent",toTopOf="parent",toBottomOf="parent",根据约束条件,这个子组件会占据父容器全部空间。这里要如何限制组件宽高比,就根据ratio的前缀而定。ratio="w,2:1",那么子组件的h=父容器高(另一边根据其他约束条件得到值),w:h=2:1, w=2h=2倍父容器高度(可能超出了显示范围),如果ratio="h,2:1",那么子组件w=父容器宽(另一边根据其他约束条件得到值),w:h=2:1,h=1/2*w=父容器宽度的一半。正常情况下ratio会按上面的方式工作

但如果出现下列情况,计算的结果很可能会出乎意料让人疑惑

如: w=100dp,h=0dp,ratio="w,2:1" 此时w已经设置为固定长度,无法先通过其他约束条件计算h,再通过ratio计算w,设置冲突。此时Android计算出的实际结果,可以视为 Android 识别到了冲突,把原本w:h=ratio 替换为 h:w=ratio 来计算未知边,也就是 w=100dp,h=0dp,ratio="w,2:1" 通过 h:w=2:1 计算未知边h,h=2w=200dp,最后得到的结果,w=100dp,h=200dp。

同理:w=0dp,h=100dp,ratio="h,2:1",h已设置为固定值,冲突,改为 h:w=2:1计算w,w=1/2*h=50dp,最后结果w=50dp,h=100dp。

记录备忘

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值