Scale drawableLeft in a button with text

I have a button with text and displayed on the left. Is there a way to make this scalable scale fit the size (height of the fill button) while maintaining 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"/> 
+6
source share
3 answers

You can resize the image to fit the button, use the getHeight() and getWidth() methods to get the size of the button and use the following function to resize the image for the button:

Resize a bitmap:

 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 resize for your button. Link

+2
source

Can u create a button (containing everything) like in a graph.

Or U can try with this -> 1. Take a layout (relative or linear) with a width and height the same as the size of your button. 2. Now place the image and text view. 3. Make the layout clickable.

0
source

You can use the function consisting of the following code in onCreate() :

  //get left drawable Drawable drawable = btn.getCompoundDrawables()[0]; int imgHeight = drawable.getIntrinsicHeight(); int imgWidth = drawable.getIntrinsicWidth(); //for dpToPixel look here: https://stackoverflow.com/a/6327095/2306907 float scale = (float) (dpToPixel(40)) / imgHeight; Rect rect = drawable.getBounds(); int newWidth = (int)(imgWidth * scale); int newHeight = (int)(imgHeight * scale); rect.left = rect.left + (int)(0.5 * (imgWidth - newWidth)); rect.top = rect.top + (int)(0.5 * (imgHeight - newHeight)); rect.right = rect.left + newWidth; rect.bottom = rect.top + newHeight; drawable.setBounds(rect); 

or see this answer , which is trying to give a β€œuniversal” solution.

0
source

Source: https://habr.com/ru/post/915928/


All Articles