Composable fillMaxSize and rotation not working - android

How can I rotate composables and still make them fill their parent?
For example, I have a Column filling the Screen with two Boxes taking up half the size.
The size of the boxes seems to be calculated before the rotation and not after.
Column(
modifier = Modifier
.fillMaxSize()
.padding(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Box(
modifier = Modifier
.rotate(90f)
.fillMaxSize()
.weight(1f)
.background(Color.Red),
contentAlignment = Alignment.Center
) {
Text("1", fontSize = 100.sp)
}
Box(
modifier = Modifier
.rotate(90f)
.fillMaxSize()
.weight(1f)
.background(Color.Blue),
contentAlignment = Alignment.Center
) {
Text("2", fontSize = 100.sp)
}
}
Edit after Thracians comment:
This looks better but the maxHeight I get seems wrong, I can see in the layout inspector that the size of the BoxWithConstraints is right
Column(
modifier = Modifier
.fillMaxSize()
.padding(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
BoxWithConstraints(modifier = Modifier.fillMaxSize().weight(1f)) {
Box(
modifier = Modifier
.rotate(90f)
.width(maxHeight)
.height(maxWidth)
.background(Color.Red),
contentAlignment = Alignment.Center
) {
Text("1", fontSize = 100.sp)
}
}
BoxWithConstraints(modifier = Modifier.fillMaxSize().weight(1f)) {
Box(
modifier = Modifier
.rotate(90f)
.width(maxHeight)
.height(maxWidth)
.background(Color.Blue),
contentAlignment = Alignment.Center
) {
Text("2", fontSize = 100.sp)
}
}

Modifier.rotate is
#Stable
fun Modifier.rotate(degrees: Float) =
if (degrees != 0f) graphicsLayer(rotationZ = degrees) else this
Modifier.graphicsLayer{} does not change dimensions and physical position of a Composable, and doesn't trigger recomposition which is very good for animating or changing visual presentation.
You can also see in my question here even i change scale and position green rectangle, position in parent is not changing.
A [Modifier.Element] that makes content draw into a draw layer. The
draw layer can be * invalidated separately from parents. A
[graphicsLayer] should be used when the content * updates
independently from anything above it to minimize the invalidated
content. * * [graphicsLayer] can also be used to apply effects to
content, such as scaling ([scaleX], [scaleY]), * rotation
([rotationX], [rotationY], [rotationZ]), opacity ([alpha]), shadow
However any Modifier after Modifier.graphicsLayer is applied based on new scale, translation or rotation. Easiest to see is drawing border before and after graphicsLayer.
Column(modifier = Modifier.fillMaxSize()) {
val context = LocalContext.current
Row(modifier = Modifier.fillMaxSize()) {
Box(
modifier = Modifier
.size(100.dp, 200.dp)
.border(2.dp, Color.Red)
.zIndex(1f)
.clickable {
Toast
.makeText(context, "Before Layer", Toast.LENGTH_SHORT)
.show()
}
.graphicsLayer {
translationX = 300f
rotationZ = 90f
}
.border(2.dp, Color.Green)
.clickable {
Toast
.makeText(context, "After Layer", Toast.LENGTH_SHORT)
.show()
}
)
Box(
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.background(Color.Yellow)
)
}
}
If you check this example you will see that even after we rotate Composable on left position of Box with yellow background doesn't change because we don't change actual form of Composable on left side.
#Composable
private fun MyComposable() {
Column(modifier = Modifier.fillMaxSize()) {
Spacer(modifier = Modifier.height(300.dp))
Column(modifier = Modifier.fillMaxSize()) {
var angle by remember { mutableStateOf(0f) }
LaunchedEffect(key1 = Unit) {
delay(2000)
angle = 90f
}
Box(
modifier = Modifier
.fillMaxSize()
.weight(1f)
.background(Color.Red)
.rotate(angle),
contentAlignment = Alignment.Center
) {
Text("1", fontSize = 100.sp)
}
Spacer(modifier =Modifier.height(8.dp))
Box(
modifier = Modifier
.fillMaxSize()
.weight(1f)
.background(Color.Blue)
.rotate(angle),
contentAlignment = Alignment.Center
) {
Text("2", fontSize = 100.sp)
}
}
}
}
Added Spacer to have uneven width and height for Boxes for demonstration.
As i posted in example gif order of rotate determines what we rotate.
modifier = Modifier
.fillMaxSize()
.weight(1f)
.background(Color.Blue)
.rotate(angle)
This sets the size, it never rotates parent but the content or child because we set size and background before rotation. This answer works if width of the child is not greater than height of the parent.
If child has Modifier.fillSize() or child's width is bigger than parent's height when we rotate as in the image left below. So we need to scale it back to parent after rotation since we didn't change parents dimensions.
#Composable
private fun MyComposable2() {
var angle by remember { mutableStateOf(0f) }
LaunchedEffect(key1 = Unit) {
delay(2000)
angle = 90f
}
Column(modifier = Modifier.fillMaxSize()) {
Spacer(modifier = Modifier.height(100.dp))
BoxWithConstraints(
modifier = Modifier
.fillMaxSize()
.padding(8.dp)
) {
val width = maxWidth
val height = maxHeight / 2
val newWidth = if (angle == 0f) width else height
val newHeight = if (angle == 0f) height else width
Column(modifier = Modifier.fillMaxSize()) {
Box(
modifier = Modifier
.border(3.dp, Color.Red)
.size(width, height)
.graphicsLayer {
rotationZ = angle
scaleX = newWidth/width
scaleY = newHeight/height
}
.border(5.dp, Color.Yellow),
contentAlignment = Alignment.Center
) {
Image(
modifier = Modifier
.border(4.dp, getRandomColor())
.fillMaxSize(),
painter = painterResource(id = R.drawable.landscape1),
contentDescription = "",
contentScale = ContentScale.FillBounds
)
}
Box(
modifier = Modifier
.border(3.dp, Color.Red)
.graphicsLayer {
rotationZ = angle
scaleX = newWidth/width
scaleY = newHeight/height
}
.size(width, height)
.border(5.dp, Color.Yellow),
contentAlignment = Alignment.Center
) {
Image(
modifier = Modifier
.border(4.dp, getRandomColor())
.fillMaxSize(),
painter = painterResource(id = R.drawable.landscape1),
contentDescription = "",
contentScale = ContentScale.FillBounds
)
}
}
}
}
}
on left we don't scale only rotate as in question
on right we scale child into parent based on height/width ratio

Related

Compose aspectRatio Modifier not based on height

I'm trying to make a simple box (same height and width) based on a Column's wrapped height (two Text Composables). Using the aspectRatio Modifier property, the height is matching the full width, even with matchHeightConstraintsFirst = true. How do I get it to become a square from the wrap_content height?
#Composable
fun CompletionSquare(questionType: QuestionType, number: Int) {
Box(
modifier = Modifier
.wrapContentHeight()
.background(color = colorResource(id = R.color.gray))
.padding(1.dp)
) {
Column(
modifier = Modifier
.background(color = colorResource(id = R.color.teal))
.aspectRatio(matchHeightConstraintsFirst = true, ratio = 1.0f)
) {
Text(text = questionType.type)
Spacer(modifier = Modifier.height(16.dp))
Text(text = number.toString())
}
}
}

Semi oval shape in Jetpack Compose

I am trying to create a custom selectable composable and for the selected indicator, I would like to have a section at the end of the composable with a rounded edge. The final look would be something like this:
What I have currently is a box at the end with the correct background and I am trying to have another box just before which will act as the rounded edge.
The issue is that I am trying to use a GenericShape within the clip modifier and play with the Path. I have use a quadraticBezierTo function but the result isn't great since the top start and bottom start edges are very sharp.
I have looked for some Oval shap in Compose but I haven't found my luck yet.
Here is my current implementation:
#Composable
fun SelectableCard(
information: #Composable RowScope.(modifier: Modifier) -> Unit,
selected: Boolean = false
) {
Card(
modifier = Modifier
.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
) {
information(
modifier = Modifier
.padding(
vertical = dimensionResource(id = R.dimen.spacing_semi_small),
horizontal = dimensionResource(id = R.dimen.spacing_small),
)
)
// Selected indicator
Box(
modifier = Modifier
.fillMaxHeight()
.clip(
GenericShape { size, _ ->
val width: Float = size.width
val height: Float = size.height
// Starting point
moveTo(width, 0f)
quadraticBezierTo(
x1 = 0f,
y1 = height / 2,
x2 = width,
y2 = height
)
}
)
.background(Color.Red)
.width(20.dp)
)
Box(
modifier = Modifier
.fillMaxHeight()
.width(60.dp)
.background(Color.Red),
)
}
}
}
You can use a GenericShape like:
class OvalCornerShape(
size: Dp
) : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
val rect = size.toRect()
val path = Path().apply {
addOval(rect)
}
return Outline.Generic(path)
}
}
and apply it to the Box. Something like:
Box(
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
) {
// Selected indicator
Box(
modifier = Modifier
.offset(x= 10.dp)
.fillMaxHeight()
.width(60.dp)
.background(Color.Red)
)
Box(
modifier = Modifier
.fillMaxHeight()
.clip(OvalCornerShape(10.dp))
.background(Color.Red)
.width(20.dp)
)
}

Jetpack Compose: expand image with restricted height

I want to show a list of elements in which each one is an expanded image on top and a title on the bottom.
The image must expand all of its available width but it must have a fixed height.
If the image is big enough I can do it, but if the image has a portrait aspect ratio it doesn't expand as I would like.
This is what I have right now:
The first image has a portrait aspect ratio, I would like it to expand to the available width but maintaining a fixed height.
This is the code for the list and each element:
#Composable
private fun List(memes: List<Meme>) {
LazyColumn(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(12.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
itemsIndexed(memes) { index, meme ->
ListElement(meme, isFirst = index == 0, isLast = index == memes.size - 1)
}
}
}
#Composable
private fun ListElement(meme: Meme, isFirst: Boolean, isLast: Boolean) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(
start = marginLat,
top = if (isFirst) 8.dp else 0.dp,
end = marginLat,
bottom = if (isLast) 8.dp else 0.dp
),
elevation = 4.dp
) {
Column {
Image(
painter = rememberImagePainter(meme.url),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(8.dp)
.clip(RoundedCornerShape(4.dp))
)
Text(meme.name, style = MaterialTheme.typography.h6, modifier = Modifier.padding(8.dp))
}
}
}
use ContentScale.FillWidth
Image(
painter = rememberImagePainter(meme.url),
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = Modifier
.fillMaxWidth()
.height(100.dp)
.padding(8.dp)
.clip(RoundedCornerShape(4.dp))
)

Jetpack Compose - Make Image scale to the available size in Column/Row

Consider the following image:
I have a Column that has an Image together with another Column that has some Text elements. What I'm trying to do is to have the Image scale uniformly to the available space. I just can't make it work.
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.Cyan)
.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.SpaceEvenly
) {
Image(
modifier = Modifier.fillMaxWidth(),
painter = painterResource(R.drawable.rocket_boy),
contentDescription = null,
contentScale = ContentScale.Fit
)
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
repeat(20) {
Text(text = "${it}")
}
}
}
One of the things that I tried was setting the size of the Image to fillMaxSize and the weight of the second Column to 1f, but it didn't do anything. Maybe I need to have the size of the second Column fixed? Any help is very appreciated.
You haven't used Modifier.weight on the correct child. It should be applied to the view, which you need to fill the rest of the parent.
The parent will divide the vertical space remaining after measuring unweighted child elements and distribute it according to this weight.
Modifier.weight has argument fill with default parameter true. This default parameter works same as Modifier.fillMaxHeight() (in case of Column), if you don't need to fill all height available, you can specify false:
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.Cyan)
.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally,
) {
val painter = painterResource(R.drawable.ic_redo)
Image(
modifier = Modifier.weight(1f, fill = false)
.aspectRatio(painter.intrinsicSize.width / painter.intrinsicSize.height)
.fillMaxWidth(),
painter = painter,
contentDescription = null,
contentScale = ContentScale.Fit
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
repeat(20) {
Text(text = "${it}")
}
}
}
It seems to your image size is less than the screen max width, for that reason the container of the image fill the width, but the image remains small, if you fill the height on the image it scales correctly but the image container fills all space leaving below the list. You could try setting and aspect ratio to the modifier to prevent container from filling all available space:
...
val painter = painterResource(id = R.drawable.ic_dismiss_24)
Image(
modifier = Modifier
.aspectRatio(ratio = painter.intrinsicSize.height /
painter.intrinsicSize.width)
.fillMaxWidth()
.fillMaxHeight(),
painter = painter,
contentDescription = null,
contentScale = ContentScale.Fit
)
...
Couldn't get it work right using a Column, but I succeeded using a ConstraintLayout and Nestor's help with the aspectRatio.
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val (button, text) = createRefs()
val painter = painterResource(R.drawable.rocket_boy)
Image(
modifier = Modifier
.aspectRatio(ratio = painter.intrinsicSize.width /
painter.intrinsicSize.height)
.padding(16.dp)
.constrainAs(text) {
top.linkTo(parent.top)
bottom.linkTo(button.top)
height = Dimension.preferredWrapContent
width = Dimension.preferredWrapContent
start.linkTo(parent.start)
end.linkTo(parent.end)
},
painter = painter,
contentDescription = null,
contentScale = ContentScale.Fit
)
Column(Modifier.constrainAs(button) {
bottom.linkTo(parent.bottom, margin = 16.dp)
top.linkTo(text.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
height = Dimension.wrapContent
}) {
repeat(5) {
Text(text = "$it")
}
}
}
But if someone thinks that it can still be done with a Column instead of a ConstraintLayout, he can post an answer and I may accept it.
If we consider the height of the parent Column - as the sum of the heights of the Image and the nested Column - it can be argued that the height of your Image should be equal to the remainder of the height, after subtracting from the height of the parent Column - the height of the nested Column.
var textInColumnSize by remember { mutableStateOf(Size.Zero) }
var globalColumnSize by remember { mutableStateOf(Size.Zero) }
val imageHeight: Dp =
LocalDensity.current.run { (globalColumnSize.height -
textInColumnSize.height).toDp() }
Column(
modifier = Modifier
.fillMaxSize()
.onGloballyPositioned { coordinates ->
globalColumnSize = coordinates.size.toSize()
}
.background(Color.Cyan)
.padding(horizontal = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceEvenly
) {
Image(
modifier = Modifier
.fillMaxWidth()
.height(imageHeight),
painter = painterResource(R.drawable.rocket_boy),
contentDescription = null,
)
Column(
modifier = Modifier
.fillMaxWidth()
.onGloballyPositioned { coordinates ->
textInColumnSize = coordinates.size.toSize()
},
horizontalAlignment = Alignment.CenterHorizontally
) {
repeat(10) {
Text(text = "$it")
}
}
}

Android Jetpack compose partial border in Box

I am trying to prepare a design in jetpack compose with a partial border on one side of the box. Here is the UI I have right now,
The background is a solid color as of now but will be replaced with a image. I want to break border on bottom left of and add some text similar to the screenshot below while keeping the background as it is.
Here is my code:
Box(modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()) {
Box(modifier = Modifier.fillMaxHeight().fillMaxWidth().background(Color(0xFF37C7D7).copy(alpha = 0.6f)))
Box(modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()
.background(Color.Transparent)
.padding(20.dp,30.dp)
.border(width = 0.8.dp, color = Color.White.copy(alpha = 0.5f), shape=RoundedCornerShape(32.dp))
)
Box(modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()
.background(Color.Transparent)
.padding(28.dp,38.dp)
.border(width = 0.8.dp, color = Color.White.copy(alpha = 0.5f), shape=RoundedCornerShape(28.dp))
)
Column(modifier = Modifier.statusBarsPadding()
.fillMaxWidth()
.fillMaxHeight().padding(20.dp,40.dp),
verticalArrangement = Arrangement.Bottom) {
Text(text = "this is Test",modifier = Modifier.padding(0.dp,30.dp))
}
}
You can prevent part of the view from being drawn with Modifier.drawWithContent and DrawScope.clipRect. Using this method, you can create the following modifier:
fun Modifier.drawWithoutRect(rect: Rect?) =
drawWithContent {
if (rect != null) {
clipRect(
left = rect.left,
top = rect.top,
right = rect.right,
bottom = rect.bottom,
clipOp = ClipOp.Difference,
) {
this#drawWithContent.drawContent()
}
} else {
drawContent()
}
}
Use it like this:
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
) {
Image(
painterResource(id = R.drawable.my_image),
contentDescription = null,
contentScale = ContentScale.FillBounds,
modifier = Modifier.fillMaxSize()
)
var textCoordinates by remember { mutableStateOf<Rect?>(null) }
Box(
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()
.background(Color(0xFF37C7D7).copy(alpha = 0.6f))
)
Box(
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()
.drawWithoutRect(textCoordinates)
.padding(20.dp, 30.dp)
.border(
width = 0.8.dp,
color = Color.White.copy(alpha = 0.5f),
shape = RoundedCornerShape(32.dp)
)
)
Box(
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()
.drawWithoutRect(textCoordinates)
.padding(28.dp, 38.dp)
.border(
width = 0.8.dp,
color = Color.White.copy(alpha = 0.5f),
shape = RoundedCornerShape(28.dp)
)
)
Column(
verticalArrangement = Arrangement.Bottom,
modifier = Modifier
.statusBarsPadding()
.padding(20.dp, 40.dp)
.onGloballyPositioned {
textCoordinates = it.boundsInParent()
}
.align(Alignment.BottomStart)
) {
Text(text = "this is Test", modifier = Modifier.padding(0.dp, 30.dp))
}
}
Result:

Categories

Resources