Hi I have a drawable object which contains a app icon.The app icon are stored in drawable object in a runtime
process, and then then setting that drawable object with an ImageView
. But the size of the app icon changes depending on the device on which my app is running.I had set the width and height of imageView
in xml as 50dp and used this code also:
image.setAdjustViewBounds(true);
image.setMaxHeight(50);
image.setMaxWidth(50);
image.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
But it didn't worked.So how can I set final size(50dp) for my imageView
so that it can appear on same size on any android device screen.
Setting width and height in xml
file is enough. You don't need to set it programmatically.
If you set width and height like this
image.setMaxHeight(50);
image.setMaxWidth(50);
The value 50 is in pixel, not dp. An image with size 50x50 pixel will look different in different devices, because the devices have different dpi.
There are folders mdpi, hdpi, xhpdi and xxhdpi in your projects. If you want display your image in 50dp, you have to generate different files:
It is because in mdpi 1 px = 1 dp, in hdpi 1dp = 1.5 px, in xhdpi 1dp = 2px and in xxhdpi 1dp = 3px
UPDATE You can just generate one image with size 150x150 pixel and put it in folder xxhdpi. App will automatically scale your image to fit other density.
By doing
image.setMaxHeight(50);
image.setMaxWidth(50);
you are setting width
and height
in pixels
. And for different devices as resulution changes it will not look same so you need to set those values in density independent pixels(dp)
. Use following method to convert your unit from dp
to pixels
according to devices density
.
public final class DimensionUtils {
private static boolean isInitialised = false;
private static float pixelsPerOneDp;
// Suppress default constructor for noninstantiability.
private DimensionUtils() {
throw new AssertionError();
}
private static void initialise(View view) {
pixelsPerOneDp = view.getResources().getDisplayMetrics().densityDpi / 160f;
isInitialised = true;
}
public static float pxToDp(View view, float px) {
if (!isInitialised) {
initialise(view);
}
return px / pixelsPerOneDp;
}
public static float dpToPx(View view, float dp) {
if (!isInitialised) {
initialise(view);
}
return dp * pixelsPerOneDp;
}
}
您可以使用TypedValue
根据提供的dp
获取px
值:
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DP, 50, getResources().getDisplayMetrics());
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.