0

I would like to draw a Transparent Rectangle in order to split my Box.

I have found in this post what I needed to clip/cut my Composable by drawing a Transparent Rect.

Here is my code:

Box(
    modifier = Modifier
        .height(35.dp)
        .fillMaxWidth()
        .clip(shape = RoundedCornerShape(8.dp))
        .fillMaxWidth()
        .drawWithLayer {
            drawContent()
            val rect = Rect(
                offset = Offset(x = size.width / 2f, y = 0f),
                size = Size(width = 10.dp.value, height = size.height),
            )
            rotate(
                degrees = 35F,
                pivot = rect.center
            ) {
                drawRect(
                    blendMode = BlendMode.SrcOut,
                    color = Color.Transparent,
                    topLeft = rect.topLeft,
                    size = rect.size,
                )
            }
        }
) {

Result :

enter image description here

This is the intended behaviour, but I don't understand why when I rotate the rectangle, it doesn't take the whole height?

EDIT:

After trying the solution by changing the height of the transparent rectangle, this is what I got.

enter image description here

It's almost the expected result, but the top part of the rectangle doesn't fit.

Funnycuni
  • 369
  • 1
  • 15

2 Answers2

1

With some trigonometry, you can achieve this.

Code inside drawWithLayer

drawContent()
val degrees = 35F
val radians = Math.toRadians(degrees.toDouble()).toFloat()

val dividerWidth = 10.dp.value

// Divider height = slant height of the divider + twice the slany height of the divider width
val dividerHeight = (size.height / cos(radians)) + (2 * dividerWidth * sin(radians))

// Both x and y offset would be required
val rect = Rect(
    offset = Offset(
        x = size.width / 2F,
        y = -(dividerHeight - size.height) / 2,
    ),
    size = Size(
        width = dividerWidth,
        height = dividerHeight,
    ),
)
rotate(
    degrees = degrees,
    pivot = rect.center,
) {
    drawRect(
        blendMode = BlendMode.SrcOut,
        color = Color.Blue,
        topLeft = rect.topLeft,
        size = rect.size,
    )
}
Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
0

This is because in reality, the perpendicular height is smaller after rotation. The good thing is you dont need trigonmetry to dynamically extend the height, the clip in your parent box will save you from render draws. just extend the smaller rectangles height. x2 is reasonable in you're use case:

size = rect.size.copy(y = rect.size.y * 2)
  • It doesn't work, even if I change height x2 or x4 or x10 – Funnycuni Jun 28 '23 at 10:47
  • Thanks for the update, true that only the bottom part gets extended. Abhimanyu posted a better answer, seems like trig ratios are necessary. But I'd like to add my 2 cents if it would be less complex by offsetting in `-x` and then increasing the size? – Blessing Charumbira Jun 29 '23 at 19:30