Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get drawable for density for API Level <15

Tags:

android

Since Android API Level 15 there is the method public Drawable getDrawableForDensity (int id, int density) to retrieve a drawable object for a specific screen density. Is there any way to do this prior to API Level 15?

like image 201
Arthur Dent Avatar asked Feb 20 '12 10:02

Arthur Dent


1 Answers

So I actually thought it could be resolved using reverse-engineering of Android APIs and the source-code as per @adtennant's suggestion. I started writing the solution it, but in the process hit a dead end as an underlying native (non-Java) API that is necessary is unavailable in later versions of Android.

If you are okay constraining this to just Bitmaps, as implied by your comment, it is possible to do this with BitmapFactory as suggested. BitmapFactory has another method:

decodeResource(Resources res, int id, BitmapFactory.Options opts)

This method accepts the additional BitmapFactory.Options which will allow you to specify the density to load. This appears to have existed since API level 1. Specifically, I believe that you can use:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inDensity = DisplayMetrics.DENSITY_MEDIUM; // whichever you want to load
options.inTargetDensity = getResources().getDisplayMetrics().densityDpi;
options.inScaled = true;

This will also scale it to the screen density if a mismatched density is loaded.

like image 51
Rajiv Makhijani Avatar answered Oct 20 '22 12:10

Rajiv Makhijani