I have a button with text and a drawable on the left. Is there any way I can make that drawable scale to it's appropriate size (fill button's height) while keeping its aspect ratio?
Relevant excerpt from my layout:
<Button
android:text="@string/add_fav"
android:id="@+id/event_fav_button"
android:layout_width="match_parent"
android:layout_height="40dp"
android:drawableLeft="@drawable/star_yellow"/>
You can resize an image on basis of the dimension of a Button, use getHeight()
and getWidth()
methods to get the size of the button and use following function to resize image for Button:
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
Now use this resized image for your button. Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With