0

I am using the following code to scale an image to 150dpx150dp and place in inside a 150dpx150dp button but the image overflows the button in all dimensions:

    float densityScale = getResources().getDisplayMetrics().density;
    float scaledImageWidth = 150 * densityScale;

    float scaledImageHeight =  150 * densityScale;
    Drawable image = getResources().getDrawable(R.drawable.user_photo);
    Bitmap bitmap = ((BitmapDrawable)image).getBitmap();
    Drawable scaledImage = new BitmapDrawable(Bitmap.createScaledBitmap(bitmap, (int)scaledImageWidth, (int)scaledImageHeight, true));
    scaledImage.setBounds(0, 0, (int)scaledImageWidth, (int)scaledImageHeight);
    ((Button)findViewById(R.id.button)).setCompoundDrawables(null, scaledImage, null, null);
    ((Button)findViewById(R.id.button)).setPadding(0,0,0,0);

enter image description here

Button and image are of the same size. Why does this overflow happen and how can it be fixed?

(I know I can use an ImageButton for this but I want to use button drawable because there are cases where I will need to add text etc.)

John L.
  • 1,825
  • 5
  • 18
  • 45
  • 1
    See [this](http://stackoverflow.com/questions/43192378/how-to-properly-remove-padding-or-margin-around-buttons-in-android) post. – azizbekian May 06 '17 at 21:25

1 Answers1

1

You need to have a smaller drawable. Button already has a background with a certain padding

enter image description here

Nicolas
  • 6,611
  • 3
  • 29
  • 73
  • How can I get rid of that padding? Or how much should I scale the image to make it fit in exactly? Is there an Android documentation about these values? – John L. May 06 '17 at 17:48
  • Here's the [9-patch drawable of a button](https://github.com/android/platform_frameworks_base/blob/4b1a8f46d6ec55796bf77fd8921a5a242a219278/tests/GridLayoutTest/res/drawable/btn_default_normal.9.png). There seems to be 6 px on the left and right side, 3 px on top and 10 pixel on the bottom. The compound drawable is centered on the view not on the button visual center, so you can't really make it fit exactly. – Nicolas May 06 '17 at 18:29
  • Just realized you are setting your setting your drawable as the top compound drawable. Compound drawables are drawn on the sides of the text. You can add negative compound drawable padding but then you need to know your text height, it would be complicated to center it correctly. – Nicolas May 06 '17 at 18:41