Lia*_*Sha 10 android android-constraintlayout android-jetpack android-jetpack-compose
当图像的宽度/高度为 4/3 时,我想将图像的开始限制为父级的开始、从上到上、从头到尾,就像app:layout_constraintDimensionRatio="H,3:4"在 Android Xml 中一样。
下面是我的代码:
ConstraintLayout(
modifier = Modifier
.wrapContentHeight()
.width(162.dp)
.clip(RoundedCornerShape(10.dp))
.background(color = Color.White)
.clickable {
//do something
}
) {
val (coverImg, title, status, date) = createRefs()
Image(
"some ignored properties",
modifier = Modifier
.constrainAs(coverImg) {
linkTo(start = parent.start, end = parent.end)
top.linkTo(parent.top)
width = Dimension.fillToConstraints
}
.height(102.dp)//I don't want to specify its height
)
Text(...)
AnyOtherLayout(...)
}
Run Code Online (Sandbox Code Playgroud)
Raf*_*iul 18
您可以在jetpack compose中使用aspectRatio修饰符。
modifier = Modifier.aspectRatio(0.75f)
Run Code Online (Sandbox Code Playgroud)
它需要两个参数,第一个参数是表示纵横比的单个浮点值。就像如果你想使用 3:4,你必须输入 3/4f 或 3/4 = .75f。
第二个是可选的,默认为 false。如果您发送 true ,它将首先考虑 Constraints.maxHeight 。
matchHeightConstraintsFirst: Boolean = false
Run Code Online (Sandbox Code Playgroud)
Sco*_*per 11
使用的问题Modifier.aspectRatio在于,使用其他约束时似乎没有考虑到这一点。长宽比实际上是由 ConstraintLayout 本身支持的
以这个布局为例,我们将一个维度限制为 16:9 的比例
ConstraintLayout(modifier = Modifier.fillMaxSize()) {
val (box) = createRefs()
val guidelineBottom = createGuidelineFromBottom(0.1f)
Box(modifier = Modifier
.background(Color.Blue)
.constrainAs(box) {
linkTo(parent.start, parent.end, startMargin = 32.dp, endMargin = 32.dp)
linkTo(parent.top, guidelineBottom)
width = Dimension.ratio("16:9")
height = Dimension.fillToConstraints
}
)
}
Run Code Online (Sandbox Code Playgroud)
这给了我们这个
如果我们然后更改guidelineBottom的偏移量以减少可用高度,我们最终会得到这样的结果
val guidelineBottom = createGuidelineFromBottom(0.9f)
Run Code Online (Sandbox Code Playgroud)
您可以使用aspectRatio修饰符:
Image(
painter = painterResource(id = R.drawable.xxx),
"some ignored properties",
contentScale = ContentScale.FillBounds,
modifier = Modifier
.constrainAs(coverImg) {
linkTo(start = parent.start, end = parent.end)
top.linkTo(parent.top)
width = Dimension.fillToConstraints
}
.aspectRatio(ratio = 4f/3f)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4816 次 |
| 最近记录: |