How to create a outlined text with filled body in Jetpack Compose

455 Views Asked by At

To create an outlined text you can apply a stroke effect to it but then it leaves the body transparent. What I want to achieve here is

enter image description here

rather than

enter image description here

For creating the stroke effect we only need to have an style like:

TextStyle(
        fontFamily = robotoFamily,
        fontWeight = FontWeight.Bold,
        fontSize = 86.sp,
        letterSpacing = 0.86.sp,
        lineHeight = 20.sp,
        textAlign = TextAlign.Center,
        color = MaterialTheme.colorScheme.surface,
        drawStyle = Stroke(
            miter = 10f,
            width = 10f,
            join = StrokeJoin.Miter
        ),
        shadow = Shadow(
            color = Color.Gray,
            offset = Offset(-16f, 16f),
            blurRadius = 8f
        )
    )

which will result in the second image. The body of the text will be transparent hence the shadow lines behind it are visible.

1

There are 1 best solutions below

2
Amir On

To have a text with a stroke in a different color I came up with this hack of having another overlaying text.

@Composable
fun SensorText(text: String) {
    Text(
        text = text,
        style = superLargeStyleOutline
    )

    Text(
        text = text,
        style = superLargeStyle
    )
}

val superLargeStyle: TextStyle
    @Composable
    get() {
        return TextStyle(
            fontFamily = robotoFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 86.sp,
            letterSpacing = 0.86.sp,
            lineHeight = 20.sp,
            textAlign = TextAlign.Center,
            color = MaterialTheme.colorScheme.surface
        )
    }
val superLargeStyleOutline: TextStyle
    @Composable
    get() {
        return superLargeStyle.copy(
            color = Color(0xFF9CB2D0),
            drawStyle = Stroke(
                miter = 10f,
                width = 10f,
                join = StrokeJoin.Miter
            ),
            shadow = Shadow(
                color = Color.Gray,
                offset = Offset(-16f, 16f),
                blurRadius = 8f
            )
        )
    }

Keen to see how others achieve the same result.