John L.
John L.

Reputation: 1953

Android Drawable Overflowing From Button Borders

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

Upvotes: 0

Views: 45

Answers (1)

Nicolas
Nicolas

Reputation: 7081

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

enter image description here

Upvotes: 1

Related Questions