Home > front end >  How can I draw bracket in compose
How can I draw bracket in compose

Time:12-08

I want to draw open-close brackets in compose and set a text in the center of them. how can i draw it?

enter image description here

CodePudding user response:

You can draw anything behind or front of your Composable using Modifier.drawBehind or Modifier.drawWithContent.

enter image description here

private fun DrawScope.drawHalfBracket() {

    val width = size.width
    val height = size.height

    drawLine(
        color = Color.Black,
        start = Offset(width * .1f, 0f),
        end = Offset.Zero,
        strokeWidth = 2.dp.toPx(),
        cap = StrokeCap.Round
    )
    drawLine(
        color = Color.Black,
        start = Offset(0f, 0f),
        end = Offset(0f, height),
        strokeWidth = 2.dp.toPx(),
        cap = StrokeCap.Round
    )
    drawLine(
        color = Color.Black,
        start = Offset(width * .1f, height),
        end = Offset(0f, height),
        strokeWidth = 2.dp.toPx(),
        cap = StrokeCap.Round
    )
}


@Composable
fun BracketAndSubscriptSample() {

    // create a variable subScript
    // enter the baselineShift to
    // BaselineShift.Subscript for subscript
    val subscript = SpanStyle(
        baselineShift = BaselineShift.Subscript,
        fontSize = 16.sp, // font size of subscript
    )


    val annotatedString = buildAnnotatedString {
        append("f")
        withStyle(subscript) {
            append("x")
        }
        append(" 0 ")
        append("o")
        withStyle(subscript) {
            append("x")
        }
        append("\n\n0")
        append(" f")
        withStyle(subscript) {
            append("y")
        }
        append(" o")
        withStyle(subscript) {
            append("y")
        }
        append("\n\n0")
        append("  0  ")
        append("1")
    }

    Text(
        annotatedString,
        fontSize = 24.sp,
        modifier = Modifier
            .drawBehind {
                drawHalfBracket()
                rotate(180f) {
                    drawHalfBracket()
                }
            }
            .padding(4.dp)
    )
}
  • Related