Image loaded from assets folder comes in different size than res/drawable

偶尔善良 提交于 2019-12-10 11:06:38

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/24580261/image-loaded-from-assets-folder-comes-in-different-size-than-res-drawable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!