Search code examples
androidandroid-jetpack-composeandroid-compose-textfieldandroid-jetpack-compose-canvas

How to outline text in Jetpack Compose


I have a Jetpack Compose Text() element that I'd like to outline in black like so this.
Anyone know how to do this? I've tried using the border() modifier, but that just adds a border around the rectangular area containing the text. I've also tried overlaying two text elements, but that doesn't quite work either.


Solution

  • The 1.4.0-alpha01 introduced a DrawStyle parameter to TextStyle function that enables drawing outlined text.

    You can use something like:

    Text(
        text = "Sample",
        style = TextStyle.Default.copy(
            fontSize = 64.sp,
            drawStyle = Stroke(
                miter = 10f,
                width = 5f,
                join = StrokeJoin.Round
            )
        )
    )
    

    enter image description here

    Before 1.4.0-alpha01 you can use a Canvas and the drawIntoCanvas function.

    Something like:

    Canvas(
        modifier = Modifier.fillMaxSize(),
        onDraw = {
                    drawIntoCanvas {
                        it.nativeCanvas.drawText(
                            "Sample",
                            0f,
                            120.dp.toPx(),
                            textPaintStroke
                        )
                        it.nativeCanvas.drawText(
                            "Sample",
                            0f,
                            120.dp.toPx(),
                            textPaint
                        )
                    }
                }
    )
    

    with these Paint:

    val textPaintStroke = Paint().asFrameworkPaint().apply {
        isAntiAlias = true
        style = android.graphics.Paint.Style.STROKE
        textSize = 64f
        color = android.graphics.Color.BLACK
        strokeWidth = 12f
        strokeMiter= 10f
        strokeJoin = android.graphics.Paint.Join.ROUND
    }
    
    val textPaint = Paint().asFrameworkPaint().apply {
        isAntiAlias = true
        style = android.graphics.Paint.Style.FILL
        textSize = 64f
        color = android.graphics.Color.WHITE
    }
    

    enter image description here