imn
imn

Reputation: 890

How to convert dp values to x and y float values for Corner radius?

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?

Upvotes: 3

Views: 3727

Answers (2)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364401

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

Upvotes: 4

cactustictacs
cactustictacs

Reputation: 19562

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

Upvotes: 1

Related Questions