How to make ImageButton in Android automatically scale based on screen density?
-
20-09-2019 - |
Question
I have an image put on an ImageButton
, which looks good on a mdpi (medium-dpi) screen. However, when the device has a hdpi (high-dpi) screen, the image is still pixel-by-pixel accurate, which look small on the device screen.
How do I make such that the image (and therefore the ImageButton
) scaled based on the density-independent pixels (dp or dip) instead of pixels?
Solution
As ponkin mentioned, 9-patches are your best bet. Combined with resource directory qualifiers (drawable-hdpi
, drawable-mdpi
, etc.) you can make assets that look good at any density and size.
An example of 9-patches and resource directory qualifiers can be found in the Multiple Resolutions Android SDK sample. The semi-transparent, black, rounded-corner background is implemented as a 9-patch with different PNGs for ldpi, mdpi, and hdpi.
OTHER TIPS
android:scaleType="fitXY"
Other choices include :
fitStart
fitCenter
fitEnd
center
cenerCrop
centerInside
matrix
Mind you i'm lazy and use really large PNG images in a raw folder.
IMHO you should look pretty close to NinePatchDrawable . There is, actually, a tool that will help you to make your icon(pictures/icons/whatever...) resizable depending on size of container. It`s really simple and works just fine for my needs. Also look at this article(part "NinePatchDrawable"), it explains the NinePatchDrawable mechanism.
A NinePatchDrawable graphic is a stretchable bitmap image, which Android will automatically resize to accomodate the contents of the View in which you have placed it as the background. An example use of a NinePatch is the backgrounds used by standard Android buttons — buttons must stretch to accommodate strings of various lengths. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension .9.png, and saved into the res/drawable/ directory of your project.
Maybe you should just specify button size in device-independent-pixels?
android:layout_width="300dip"
android:layout_height="50dip"