1

this is the function i'm trying to import https://developer.android.com/reference/kotlin/androidx/compose/ui/unit/Density#(androidx.compose.ui.unit.DpRect).toRect()

here is my code

    val cardWidth = 180f.dp
    val cardHeight = 270f.dp
    val fullHeight = 296f.dp 
    val focusRect = DpRect(0f.dp, 0f.dp, cardWidth, fullHeight).toRect()

i have tried importing like

import androidx.compose.ui.unit.Density.toRect
import androidx.compose.ui.unit.toRect
import androidx.compose.ui.unit.DpRect.toRect

but non of them works.

Mars
  • 873
  • 1
  • 11
  • 24
  • Have you tried getting your IDE to do the import? For example, in IntelliJ, move the cursor to the `focusRect` line, immediately after the last `.`, then invoke the code completion (e.g. by pressing Ctrl+Space). The relevant function should appear in the resulting list, and selecting it should add the import as well as inserting its name. — Or if it's _not_ shown in the list, then you can't call it there, e.g. because the receiver is the wrong type, or that library isn't in your dependencies. – gidds Oct 14 '22 at 18:53

1 Answers1

1

That's an extension function inside a Density object, a member function - you need to run it within that context. You can't just import it and use it anywhere, because it's internal to that object. (See the comment in the first example here.)

So you need to do something like this:

val focusRect = Density(density = 2f).run {
    DpRect(0f.dp, 0f.dp, cardWidth, fullHeight).toRect()
}

which, import limitations aside, makes sense - how can you convert dp values to px values if you haven't defined the density involved? You can see how it works in the source code:

fun DpRect.toRect(): Rect {
    return Rect(
        left.toPx(),
        top.toPx(),
        right.toPx(),
        bottom.toPx()
    )
}

fun Dp.toPx(): Float = value * density

where density is a property on the Density object, the one we passed in as a parameter. Basically you can create a Density and use it to perform conversions based on that density. The extension functions don't make sense outside of that context, right?

cactustictacs
  • 17,935
  • 2
  • 14
  • 25