Hey, I'm testing different methods for drawing a c...
# compose
m
Hey, I'm testing different methods for drawing a circle with a stroke. Why I'm getting a different result when using those 2 methods?
Copy code
// first method - result on the left
  Canvas(modifier = Modifier.size(50.dp)) {
    drawCircle(Color.Blue)
    drawCircle(Color.Green, style = Stroke(width = 2.dp.value))
  }
  / second method - result on the right
  Surface(
    shape = CircleShape,
    color = Color.Blue,
    border = BorderStroke(2.dp, Color.Green),
    modifier = Modifier.size(50.dp),
    content = {}
  )
Ah I see - in the first example
Stroke(width = 2.dp.value)
is wrong.
2.dp.value
returns 2 and not pixel value. The correct way would be
Stroke(width = 2.dp.toPx())
. Now it looks almost the same, except for the fact that green circle is outside of composable bounds as you can see on first screenshot. Why is it like this?
s
I think composables don't clip to their bounds by default; I'd guess it's simply a different implementation between Stroke and BorderStroke here
m
Makes sense. Speaking of clipping - If I draw a 20dp x 20dp circular surface with a 2dp border stroke then it looks clipped at the top, bottom, left and right. Do you know why is it like this?
Looks fine without the border:
s
hm not sure, may be a precision issue, but I don't really know enough about the internals. Hopefully someone from the compose team has a definitive answer
1
m
👍
a
It’s because Compose UI considers the size you specified as the size of the center of the stroke. You can read this thread if you want to know more.
m
I see, thanks Albert!