Get font scaling factor to calculate the fontsize
I just found in the source code of Settings.System
this function:
/** @hide */public static void getConfigurationForUser(ContentResolver cr, Configuration outConfig, int userHandle) { outConfig.fontScale = Settings.System.getFloatForUser( cr, FONT_SCALE, outConfig.fontScale, userHandle); if (outConfig.fontScale < 0) { outConfig.fontScale = 1; }}
There is however the FONT_SCALE
in usage so I checked for that Configuration
class where the documentation points to getResources().getConfiguration()
. So I counld fix my code by using:
float scale = getResources().getConfiguration().fontScale;
Since my question was about to calculate the correct font size in pixel here is the way I use it nowerdays in Kotlin:
val Number.dpInPx: Int get() = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, toFloat(), Resources.getSystem().displayMetrics).toInt()val Number.spInPx: Int get() = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, toFloat(), Resources.getSystem().displayMetrics).toInt()
The usage is:
val textSize = 42.spInPxval padding = 8.dpInPx