chethaase / ShapesDemo

Demo apps showing how to use the AndroidX :graphics:graphics-shapes: library
Apache License 2.0
188 stars 19 forks source link

How to clip RoundedPolygon to Box modifier ? #2

Open mistrydarshan99 opened 1 year ago

mistrydarshan99 commented 1 year ago

I have a below composable function in which I need to clip RoundedPolygon but not able to clip because clip function take Shape as a parameter.

Is there any way to clip RoundedPolygon ?

@Composable
private fun HexagonRow(task: Task) {

    val roundedPolygon = RoundedPolygon(numVertices = 6)

    Box(
        modifier = Modifier
            .fillMaxWidth(0.55f)
            .height(200.dp)
            .clip() // need to clip RoundedPolygon
            .background(Color.LightGray),
        contentAlignment = Alignment.Center
    ) {
        Text(text = "Test")
    }
}
LouisCAD commented 9 months ago

You can try using the drawWithContent modifier, and draw your shape with BlendMode.DstIn after drawing the content.

yschimke commented 8 months ago

I think Outline.Generic(shape.toPath()) should work if you implement compose Shape.

yschimke commented 8 months ago

Something like

class PillShape(
    val dpSize: DpSize
) : Shape {
    val height = dpSize.height.value

    val width = dpSize.width.value

    val Pill = RoundedPolygon.pill(
        smoothing = 0.3f,
        height = height,
        width = width,
        centerX = width,
        centerY = height
    )
    val scaleFactor = height

    override fun createOutline(
        size: Size,
        layoutDirection: LayoutDirection,
        density: Density
    ): Outline {
        return Outline.Generic(Pill.toPath().apply {
            // Why?
            transform(scaleMatrix(sx = 1.35f, sy = 1.35f))
        }.asComposePath())
    }
}