[英]Is there something like ConstraintLayout's "dimensionRatio" property in Jetpack Compose?
當圖像的寬度\/高度為 4\/3 時,我想將圖像的開始限制為父的開始,從上到下,從端到端,就像 Android Xml 中的
app:layout_constraintDimensionRatio="H,3:4"<\/code> 。
下面是我的代碼:
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(...)
}
您可以在 jetpack compose 中使用 aspectRatio 修飾符。
modifier = Modifier.aspectRatio(0.75f)
它需要兩個參數,第一個是表示該縱橫比的單個浮點值。 就像如果你想使用 3:4 你必須輸入 3/4f 或 3/4 = .75f。
第二個是可選的,默認為 false。 如果您發送 true,它將首先考慮 Constraints.maxHeight。
matchHeightConstraintsFirst: Boolean = false
您可以使用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(4f/3f)
)
使用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
}
)
}
這給了我們這個
如果我們然后更改 guidelineBottom 的偏移量以減少可用高度,我們最終會得到這個
val guidelineBottom = createGuidelineFromBottom(0.9f)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.