6

I need to scale the background image of a button but can't turn it into a Bitmap. Here is the code right now:

int height = 50;
int width = 80;

Button b = new Button (this);
b. setBackgroundResource(R.drawable.btn);

Now I need to scale "R.drawable.btn" according to the "height" and "width". The setBackgroundResource won't accept a Bitmap. How do I do that?

Thank you.

BinaryMonster
  • 63
  • 1
  • 1
  • 5
  • Because of your text "but can't turn it into a Bitmap", I fear that the second half of my answer, below, is not applicable to your question. Do you really need to keep from turning the resource "R.drawable.btn" into a Bitmap? If so, to satisfy my curiosity and to help generate a better answer, why? – David Manpearl Mar 26 '13 at 01:47
  • Because the btn.setBackgroundResource doesn't let me set a Bitmap as a background. I think I also tried btn.setBackgroundDrawable, now I'm going to try it again. – BinaryMonster Mar 26 '13 at 19:01

2 Answers2

18

You can allow the layout parameters to control the scale or you can scale the image yourself.

Allow the layout to scale the image:

b.setBackground(getResources().getDrawable(R.drawable.btn));

Scale the image manually:

Bitmap original = BitmapFactory.decodeResource(context.getResources(), R.drawable.btn);
Bitmap b = Bitmap.createScaledBitmap(original, width, height, false);
Drawable d = new BitmapDrawable(context.getResources(), b);
button.setBackground(d);

Warning: The image may not appear onscreen scaled exactly as you expect. This is because depending on the layout parameters of your Button, Android may additionally scale the image based on the hardware screen density of your device.

Xiao
  • 1,552
  • 2
  • 22
  • 20
David Manpearl
  • 12,362
  • 8
  • 55
  • 72
0

this will turn a bitmap into a drawable

image = new BitmapDrawable(getResources(),MenuScreen.image1);

image is the drawable and image1 is the bitmap

JRowan
  • 6,824
  • 8
  • 40
  • 59