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

Compose drawText going off screen


I'm using the following code to draw text onto a Canvas, but the text as you can see from the photo is going off the screen, rather than adhering to the width parameters i issue to the Canvas, why is this happening?

This doesn't seem to happen if i use the older android canvas, possible compose bug?

 Box(
    modifier = Modifier
        .fillMaxWidth()
) {
    Canvas(
        modifier = Modifier.width(500.dp),
        onDraw = {
            drawIntoCanvas {
                it.nativeCanvas.drawText(
                    text,
                    0f,
                    120.dp.toPx(),
                    textPaintStroke(context = context)
                )
                it.nativeCanvas.drawText(
                    text,
                    0f,
                    120.dp.toPx(),
                    textPaint(context = context)
                )
            }
        }
    )
}

fun textPaintStroke(
    context: Context
): NativePaint {
    val customTypeface = ResourcesCompat.getFont(context, R.font.baloo2_semi_bold)

    return 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
        typeface = customTypeface
    }
}

fun textPaint(
    context: Context
): NativePaint {
    val customTypeface = ResourcesCompat.getFont(context, R.font.baloo2_semi_bold)

    return Paint().asFrameworkPaint().apply {
        isAntiAlias = true
        style = android.graphics.Paint.Style.FILL
        textSize = 64f
        color = android.graphics.Color.WHITE
        typeface = customTypeface
    }
}

enter image description here


Solution

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

    You can use something like:

    val longText by remember {
        mutableStateOf("Choose the flash card which matches...!")
    }
    
    Box(
        modifier = Modifier
            .fillMaxWidth()
    ) {
    
        Canvas(modifier = Modifier.fillMaxSize()){
            //....
        }
        Text(
            text = longText,
            style = TextStyle.Default.copy(
                fontSize = 64.sp,
                drawStyle = Stroke(
                    miter = 10f,
                    width = 5f,
                    join = StrokeJoin.Round
                )
            )
        )
    }
    

    enter image description here