Search code examples
androidandroid-jetpack-compose

Why can I draw a line out of the canvas when I use Jetpack Compose?


In my mind, I can draw something inside a canvas when I use Jetpack Compose.

The Code A set a canvas with size(50.dp), so I think I can only draw something inside the area.

But I get Image A when I run Code A, the line is out of the area.

Why can I draw a line out of the canvas when I use Jetpack Compose?

Code A

@Composable
fun ScreenHome_Watch(
    modifier: Modifier = Modifier   
){
    Box(
        modifier = modifier
    ) {
        Box(
            modifier = Modifier.matchParentSize()
        ) {
            Canvas(
                modifier = Modifier.size(50.dp).background(Color.Red)
            ) {
                drawLine(
                    Color.Blue,
                    start = Offset(0f, 0f),
                    end = Offset(200f, 200f),
                    strokeWidth = 5f
                )
            }
        }

    }
}

Image A

enter image description here


Solution

  • I think there is nothing wrong with drawing outside of Canvas. Even if your Canvas has 0.dp size you can still draw anywhere, drawing doesn't depend on size unless you decided to clip your Composable with functions below.

    You have always have option to clip drawing inside your Composable with Modifier.clipToBounds() or

    Modifier.graphicsLayer{
         clip = true
         shape = your shape
    }
    

    Being able to draw outside Canvas creates many possibilities such as when zooming an image you will be able draw it anywhere on screen. Check my question here and this one to see how it let's you draw shapes with gestures when needed.