I am trying to size a canvas based on an image tha...
# compose-desktop
y
I am trying to size a canvas based on an image that I draw into the canvas, but there is a mismatch between the size the canvas expect (dp) and the size of the image (pixels). Is there a way to go around this?
Copy code
@Composable
fun Panel(image: ImageBitmap) {
    Canvas(modifier = Modifier
        .size(image.width.dp, image.height.dp) // doesn't work (mismatch size)
        .border(1.dp, Color.Red)) {
        drawIntoCanvas { canvas ->
            canvas.withSave {
                canvas.drawImage(image, Offset(0f, 0f), Paint())
            }
        }
    }
}
k
What kind of a mismatch?
y
dp != pixel
k
You can look at
LocalDensity
to convert between the two
z
you want
toDp()
not
dp
dp
means “this value is a dp”,
toDp()
means “this value is a pixel and I want to convert it to a dp in the current density”
y
Using combination of the 2, it now works
Copy code
val canvasWidth = with(LocalDensity.current) { image.width.toDp() }
Thank you
toDP()
does not work on its own
k
Yes, it needs a proper context
z
Yep, it’s only available when there’s a
Density
in the receiver
y
thank you for the help. this has resolved my problem