14

I have an ImageButton, I'm using the included @android:drawable/ic_menu_more image. But it's too large. What's the best way to resize that so it fits into my form better? Also, can it be rotated within the xml? (just once, not based on state)

Roger
  • 4,181
  • 8
  • 40
  • 60

5 Answers5

34

try setting android:background instead of android:src for setting the image on the button. That might help in your case, since it will stretch the image to your button's size. Also, you will have to specify fixed dimensions for the buttons (use dip instead of px). Example:

<ImageButton
     android:background="@drawable/ic_menu_more"
     android:layout_width="50dip"
     android:layout_height="50dip" />
Anubian Noob
  • 13,166
  • 6
  • 49
  • 73
zrgiu
  • 6,075
  • 1
  • 31
  • 35
  • 2
    for those doing it programatically, use setbackgrounddrawable or setbackground instead of setimageresource – Adam Johns Jul 09 '13 at 15:35
  • I am having problem with changing icon color now: `android:tint="#D50000"` not working while `android:backgroundTint="#D50000"` isn't available below v21 – fWd82 Jul 01 '21 at 12:21
4

From steven-byle's solution (https://stackoverflow.com/a/15117536/1741997), he says:

"...Use an android:scaleType="fitCenter" to have Android scale the images, and android:adjustViewBounds="true" to have them adjust their bounds due to scaling..."

It works for me

cesargastonec
  • 394
  • 5
  • 15
1

You can use NinePatchDrawable... A resizeable bitmap, with stretchable areas that you define.

http://developer.android.com/reference/android/graphics/drawable/NinePatchDrawable.html

Brandon Frohbieter
  • 16,827
  • 3
  • 36
  • 61
0

The way I solved this problem is to create a bitmap from the drawing resource in question then transform it into a scaled bitmap with the desired size. I also set the background to transparent to only show the image.

    int height = 300;
    int width = 500
    Bitmap bmp;
    bmp = BitmapFactory.decodeResource(getResources(), R.drawable.myresourcename);
    bmp = Bitmap.createScaledBitmap(bmp, width, height, true);
    ImageButton imageButton = new ImageButton(this.getActivity());
    imageButton.setImageBitmap(bmp);
    imageButton.setBackgroundColor(Color.TRANSPARENT);

Then add it to a layout.

musterjunk
  • 322
  • 2
  • 13
0

Applying cesargastonec's answer will fit the image in your ImageButton without much room to spare. If you are using a png, you can move the image to a bigger background to get an even smaller image.

For example, moving a 48x48 image in a 256x256 background to a 512x512 background will half its size in an ImageButton with android:scaleType="fitCenter".

This approach is best applied to an image you intend to only use in ImageButtons as it may be awkwardly scaled elsewhere and have a deceptively large clickbox.

Peter
  • 11
  • 2