Welcome to this painful matter! :)
Basically
If you have control over your image size (case of the resources you use such as drawables, assets or pre defined size images) you just have to do some calculus to guarantee your ImageView
has the correct size to fit your image along different screens.
The framework already supplies APIs for this kind of stuff at Runtime
, but you don't even need to do it in code. Usually when working with UI designers , they will(should) hand to you the measure specs of all screen densities and UI elements for complex views, or at least the specs following the base density (MDPI) , so you can calculate the rest yourself. Either way, you can get to these values and use it accordingly to your density with values/dimens
. Use scaleType=fitXY
and adjustViewBounds=true
, as you have already seen, and you are good to go. Lots of references:
When you don't have control over the images size
When you have no control over the image size you need to show (when it is uploaded to somewhere with no size rules, for instance) , you have several approaches you can adopt to try to keep the aspect ratio at Runtime
. You can look for this and use what seems to serve you the most. Recently, I've been using Picasso for my image loader and found a way, not to resize images for say (even though Picasso does resize images when needed), but to bypass this situation with a very simple and elegant approach:
Picasso.with(context).load("image_url").fit().centerCrop().into(imageView);
This produces this kind of behavior , like in WhatsApp:
Where the image does not get distorted and the main part(center) is shown, no matter the size of the ImageView
. Course you should still use the correct size of your view accordingly to your current screen size and density to guarantee the best experience.