Java (Android): How to scale a drawable without Bitmap?

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?

  • How to force ViewPager to re-instantiate its items
  • Can't find in support design library
  • Android InstrumentationTestRunner XML output for Hudson ingestion
  • Android: OutOfMemoryError while uploading video - how best to chunk?
  • Android: make everything around Dialog darker than default
  • How to run Android-x86 4.2 iso on VM VirtualBox?
  • Thank you.

    Related posts:

    How to add custom mime type?
    PhoneGap not firing deviceready on Android 4.2
    Make Recycler View show rows from bottom
    Activity life cycle methods : onPostResume significance
    most efficient way to play a sound when button is clicked
    getItem() method is getting called twice when using Fragment Pager Adaptor
  • Not able to make xmpp connection between my app server and GCM's CCS using XMPPHP library
  • how to add Go button in android SoftKeyBoard and its functionality?
  • How re-run failed test in Espresso? - brainstorming
  • How to solve setMyLocationEnabled permission requirement?
  • Ellipsize not working for textView inside custom listView
  • ActivityLifecycleCallbacks are not triggered when activity is killed through “Don't keep activities”
  • 2 Solutions collect form web for “Java (Android): How to scale a drawable without Bitmap?”

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

    Allow the layout to scale the image:


    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);

    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.

    this will turn a bitmap into a drawable

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

    image is the drawable and image1 is the bitmap

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.