HelloCW
HelloCW

Reputation: 2255

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

Upvotes: 3

Views: 2050

Answers (2)

Muhammad Bilal
Muhammad Bilal

Reputation: 1

Here is the example to draw custom shapes with Canvas Path :

   Box(Modifier.size(200.dp).drawBehind {
    val path = Path().apply {
        moveTo(200f, 200f)
        lineTo(200f, 50f)
        lineTo(100f, 200f)
        close()
    }
    drawPath(path, color =Color.Cyan )
})

Upvotes: 0

Thracian
Thracian

Reputation: 66674

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.

Upvotes: 4

Related Questions