I try make my application support multiple density. As we know if we want to get value of density we use syntax like this "getResources().getDisplayMetrics().density;".
My question is how to get picture from some folder. let say i have a variable :
float myDensity = getResources().getDisplayMetrics().density;
when myDensity return 1.0 , I want take picture from drawable-mdpi, when it return 0.75 i want to take picture from drawable-ldpi, and same with picture in folder drawable-xhdpi, and folder drawable-xxhdpi. i try to make it like this treepict.setImageResource(R.drawable-hdpi.tree);
but that i get just error.
anyone can help me how to do this?
you can not set like R.drawable-hdpi.tree
. only R.drawable.tree
is created for every drawable tree images. if you use R.drawable.tree
then system will choose automatically depending on the screen density.
now if you want different image for diffeent resolution you can use different images to show in your app.
The system should do this automatically for you.
So let's say you have a image, image.png
, made specifically for each density. Your code shouldn't need to know the actual density in order to operate. It should just focus on assigning the conceptual image to the image view.
So in the project's res folder:
<YourProjectHome>/res/
There are folders:
drawable-ldpi
drawable-mdpi
drawable-hdpi
drawable-xhdpi
drawable-xxhdpi
drawable-xxxhdpi
Just put the image specific to each density in the corresponding folder, and name them exactly the same. In this example it would be just image.png
Then in your code you would just do
treepic.setImageResource(R.drawable.image);
There are some cases where yes you would like to specify the image to be of a specific density. There is rather new call, getDrawableForDensity()
This one will look up a specific version of a drawable for the given density. However for the common case it is overkill. It's only really necessary if you were to be downsampling. Ie You don't have a hdpi version of something but like you have an xxxhdpi version and want to scale it down to look semi ok.
您可以为文件夹中的相同图片使用唯一名称:R.drawable-hdpi.tree_hdpi R.drawable-mdpi.tree_mdpi等。
Everything about pix density in your screen is managed by Android. you don't need to set or locate the images. android will choose the image correct image for you
you can use R.drawable.tree
to choose the image automatically for you
so just place all the different density image into appropriate folder with same name. and call them by R.drawable.tree
Android will choose correct one depends on the screen density for you
/drawable should be reserved for assets that you don't either care which device or for xml drawable assets
if you need more info about screen support resolutions goto this link
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.