I am struggling with the implementation of `dimens...
# compose
b
I am struggling with the implementation of
dimensionResource(...)
. At the moment i am setting a custom LocalDensity if the device has a certain width. The reason I am setting a custom density is to achieve the autoscaling of composables, e.g. when an image has a size in COMPACT mode from 50.dp (e.g. =150px) it should be bigger in MEDIUM mode (e.g. =150px * 1.2 = 180px)
Copy code
val density = LocalDensity.current.density
val fontScale = LocalDensity.current.fontScale
val scaleFactor = if (windowSizeClass == MEDIUM) 1.2F else 1.0F

CompositionLocalProvider(
  LocalDensity provides Density(density = scaleFactor * density, fontScale = fontScale)
) {
   val dpDirectly = 130.dp
   val dpViaResources = dimensionResource(id = R.dimen.dimen_130)
   
   // windowSizeClass == COMPACT
   // dpDirectly = 130.dp
   // dpViaResources = 130.dp

   // windowSizeClass == MEDIUM
   // dpDirectly = 130.dp
   // dpViaResources = 108.33333.dp -> WRONG VALUE!!!!
}
The problem is the dimensionResource function, because here the displayMetrics are used and they have a different density than the LocalDensity:
Copy code
fun dimensionResource(@DimenRes id: Int): Dp {
    val context = LocalContext.current
    val density = LocalDensity.current
    val pxValue = context.resources.getDimension(id) // this returns the wrong value because here the DisplayMetrics are used
    return Dp(pxValue / density.density) -> this tries to get the correct value by dividing through the LocalDensity
}
The main problem is the LocalDensity and DisplayMetrics have different density values. Two questions: 1. Can it be done like this 2. If not what is the best way to achieve autoscaling of dp and sp values?