2

I'm creating dashed rectangle with 12 dp corner radius.

I'm using canvas for that. In that we can't give corner radius in dp or px.

  Canvas(modifier = Modifier.fillMaxSize()) {
            drawRoundRect(color = Color.Red, style = stroke, cornerRadius = CornerRadius(35f, 35f))
        }

In that I put 35f because it resembles 12 dp. Is there any way to use dp or is there any way to covert dp/px to float xy values?

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
imn
  • 620
  • 1
  • 7
  • 19

2 Answers2

3

The Canvas works with a DrawScope which provides a Density interface.
With it you can use the Dp.toPx() function:

Canvas(modifier = Modifier.fillMaxSize()) {
    val px = 12.dp.toPx()
    drawRoundRect(color = Color.Red,style = stroke, cornerRadius = CornerRadius(px))
}

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
1

dp is a "general size on the screen" value. The actual number of pixels that is depends on the device's screen density - a higher-density screen crams a lot more pixels into a given space, so a given dp value will translate into a higher px value

You can get that density factor from Resources:

context.resources.displayMetrics.density

and that value will give you your dp-to-px scaler. (You need that because 35f will look very different on a hdpi screen compared to an xxxhdpi one)

Once you have your px value, you can just use it. You'll have a float after you multiply by density but you can just call toInt if you need to (or toFloat if you're going the other way). They're just different ways of expressing a value - what's important is that value is correct, that it represents the right number of pixels etc, whether it's 100 or 100f

cactustictacs
  • 17,935
  • 2
  • 14
  • 25