I have the following drawable, called small
:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:dither="true"
android:shape="oval"
>
<size
android:height="10dp"
android:width="10dp"
/>
<solid android:color="#FF666666" />
</shape>
I would like to access the height
and width
defined in size
. This is the line that gets the drawable:
val drawable: GradientDrawable = getDrawable(R.drawable.small) as GradientDrawable
GradientDrawable
does not seem to have any accessors that provide the size
and its fields. Even running in the debugger I see no fields that are set to 10dp
. Is there a way to access the size
height
and width
?
The suggestion of @CommonsWare in the comments is correct you have to use getIntrinsicHeight()
and getIntrinsicWidth()
to programmatically get the Drawable size but you have to convert those values from pixels to dps to access them in dp values.
Example:
val drawable: Drawable = ContextCompat.getDrawable(this, R.drawable.small) as Drawable
val heightDp = pxToDp(this, drawable.intrinsicHeight.toFloat())
val widthDp = pxToDp(this, drawable.intrinsicWidth.toFloat())
with the below helper function to convert the pixels to dps:
fun pxToDp(context: Context, px: Float): Float {
return px / context.resources.displayMetrics.density
}
Based on your example above the val heightDp
and the val widthDp
both will have 10dp value.