https://kotlinlang.org logo
#compose
Title
# compose
f

fengdai

05/19/2022, 5:10 AM
In the view system, a child view in a FrameLayout can be bigger than its parent, and be clipped to show only part of its content. How can I achieve this effect in Jetpack Compose?
b

Ben Trengrove [G]

05/19/2022, 5:18 AM
Modifier.clipToBounds()
or get fancy with
Modifier.clip(CircleShape)
f

fengdai

05/19/2022, 5:30 AM
The problem is that the child can’t be bigger than its parent’s bounds in Jetpack Compose, so you have nothing to clip.
Here is a simplest example:
Copy code
Box(
    modifier = Modifier.fillMaxSize()
) {
    Text(
        text = "Very Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong",
        modifier = Modifier.width(1000.dp),
        fontSize = 38.sp
    )
}
Oh. I found wrapContentWidth(unbound = true) works:
Copy code
Box(
    modifier = Modifier.fillMaxSize()
        .wrapContentWidth(unbounded = true)
) {
    Text(
        text = "Very Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong",
        modifier = Modifier.width(1000.dp),
        fontSize = 38.sp
    )
}
t

Tobias Suchalla

05/19/2022, 5:51 AM
There's also the possibility of modifying the constraints of the child:
Copy code
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layout
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.singleWindowApplication

fun main() = singleWindowApplication {
    Box(
        modifier = Modifier
            .size(100.dp, 100.dp)
            .border(Dp.Hairline, Color.Black)
            .clipToBounds(),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "Loooooooooooooooooooooooong",
            modifier = Modifier.withoutWidthConstraints()
        )
    }
}

// <https://github.com/JetBrains/compose-jb/blob/master/examples/widgets-gallery/common/src/commonMain/kotlin/org/jetbrains/compose/demo/widgets/ui/utils/LayoutModifiers.kt>
fun Modifier.withoutWidthConstraints() = layout { measurable, constraints ->
    val placeable = measurable.measure(constraints.copy(maxWidth = Int.MAX_VALUE))
    layout(constraints.maxWidth, placeable.height) {
        placeable.place(0, 0)
    }
}
It does feel somewhat hacky, though :D
f

fengdai

05/19/2022, 5:57 AM
@Tobias Suchalla Thanks!
a

Adam Powell

05/19/2022, 1:15 PM
If this weren't possible then it also wouldn't be possible to write scrolling containers and modifiers 🙂
😂 2
6 Views