How can I set width, height, size to px in compose...
# compose
c
How can I set width, height, size to px in compose? My app is used in desktop and mobile. When the project was in XML, px unit covers all the devices. which means, it fits the device size. But in compose dp and sp are fixed as a unit param. So, in Desktop device, it look very small. Is there any way to make it look Okay?
e
You say this but I am not sure a single px size would still look okay on both a (fullscreen) desktop and mobile device. It will still be either too big or too small on one of those devices, more so if it was a hardcoded px value. Feel free to post screen shots to counter this. To answer, however, you can probably override the
Density
of the desktop app so that it is x times bigger for the same size on mobile. OR You could create a
Int.pxAsDp
read composable that will allow you define px dimensions as Dp. and use that everywhere
Copy code
val Int.pxAsDp
@ReadOnlyComposable
@COmposable
  get() = with(LocalDensity.current) { toFloat().toDp }
c
Screen Shot 2023-02-21 at 4.03.16 PM.png
the largest one is desktop and the size must look bigger.
I used size something like this.
Copy code
Modifier.width(with(LocalDensity.current){209.3.dp})
         .height(with(LocalDensity.current){136.7.dp})
e
Those declarations do nothing differently from just setting the dp value I’m afraid. Infact the IDE should report to you that the density/
with
part is unused!
Anyways try the extension function I posted and you can use actual pixels wherever a Dp is required. I dont know how that is supposed to solve your actual issue but 🤷🏾
c
What declarations?
e
Copy code
with(LocalDensity.current){209.3.dp}
.dp
still just calls the Dp constructor. You need
.toDp
instead
g
the size must look bigger.
So you just want to scale it up? I feel that better solution, if you want to increase size on larger screens, would be use different sizes selected by WindowSizeClass not try to just scale it up, dp wouldn’t help in this case anyway, because dp is specified by device and they are not equal for different devices anyway, so cannot be used for your case, as I understand it
Just my 2 cents, if your desktop/tablet example would just scale as phones, it would look very strange for me. How your design suppose too look like on such screen?
918 Views