I have a PNG image that I want to display in my application.
In the layout file (.xml) I set the width and height to 50dp (density-independent). But what should be the size of my resource(.png) files?
I thought about this (calculation based on density ratios):
Or is one png file in "/res/drawables" enough that is 50px wide?
You will have to create 4 images. mdpi
will be the baseline, meaning mdpi
is 100%. Others follow this formula:
Place each image in the proper resource folder, drawable-ldpi
, drawable-mdpi
, drawable-hdpi
, drawable-xhdpi
. Android will choose the proper drawable depending on the current device.
Then, in your layout simply wrap_content
your width and height, there is no need to specify any fixed size:
<ImageView
android:src="@drawable/my_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
It's not enough to have just one image. You have to put a different image in each resource folders ( drawables-ldpi , drawables-mdpi , drawables-hdpi and drawables-xhdpi ).
Please note that 50dp
is not equal with 50px
You can make use of this formula:
px = dp * (dpi / 160)
You can find other useful tips here .
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.