2

In my project I was loading images dinamically from the folder drawable-hdpi into an ImageSwitcher like this:

int[] images = new int[2];
logoImage = (ImageSwitcher) findViewById(R.id.logo_image);
images[0] = getResources().getIdentifier(ej.getImagemResource(), "drawable", getPackageName());
images[1] = getResources().getIdentifier(ej.getImagemResolvidaResource(), "drawable", getPackageName());
//...
logoImage.setImageResource(images[0]);

but for design issues, since it will be like 600 hundred little images 300 x 300 pixels each I decided to put them all into the assets folder and start to load them like:

Drawable[] images = new Drawable[2];
images[0] = Drawable.createFromStream(getAssets().open(ej.getImagemResource() + ".png"), null);
images[1] = Drawable.createFromStream(getAssets().open(ej.getImagemResolvidaResource() + ".png"), null);
//...

The problem is that in the second way the image size is displayed very differently depending on the device density (I guess), but when the images were into the drawable-hdpi folder they were displayed just fine in any density.

How do I solve this? Or is there a problem to have 600 hundred images into the drawable-hdpi folder? Which is the 'right' way to do this?

Thanks in advance

João Menighin
  • 3,083
  • 6
  • 38
  • 80

1 Answers1

5

When you put a bitmap in a drawable-<density> folder, and there is no variant for the device's exact display density, the framework will auto-scale it considering the ratio between <density> and the device's density.

This is done so that the image dimensions, in dps, remains constant between devices (and that you are not obligated from providing a variant for each possible density).

When you load from assets, the "source" density is unknown, so this autoscaling is not performed. Hence, the difference.

If you want to load the image from the assets "as if it were hdpi", you can do something like:

Options opts = new BitmapFactory.Options();
opts.inDensity = DisplayMetrics.DENSITY_HIGH;
drawable = Drawable.createFromResourceStream(context.getResources(), null, is, srcName, opts);

That said, I don't see any problems at all with including all the files in drawable folders.

matiash
  • 54,791
  • 16
  • 125
  • 154
  • Thanks for the answer. I guess I will put everything on the res/drawable since it seems more easy to do so. Just one thing: Setting this option.inDensity as DENSITY_HIGH won't do the autoscaling as well, will it? I should set the Density to the density of the device, right? Thanks again – João Menighin Jul 04 '14 at 21:02
  • 1
    @JoãoMenighin Actually, it will. You're basically telling it "treat this drawable as if it were inside the drawable-hdpi folder". But nevertheless, going the other way is probably better. :) – matiash Jul 04 '14 at 21:05