【问题标题】:Scale drawableLeft in button with text使用文本在按钮中缩放 drawableLeft
【发布时间】:2012-05-16 17:49:12
【问题描述】:
我在左侧有一个带有文本的按钮和一个可绘制对象。有什么方法可以使可绘制的比例达到适当的大小(填充按钮的高度),同时保持其纵横比?
我的布局的相关摘录:
<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"/>
【问题讨论】:
标签:
android
button
drawable
scaling
【解决方案1】:
您可以根据按钮的尺寸调整图像大小,使用getHeight()和getWidth()方法获取按钮的大小,并使用以下函数调整按钮的图像大小:
调整位图大小:
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;
}
现在为您的按钮使用这个调整大小的图像。
Reference
【解决方案2】:
你可以在图形中创建一个按钮(包含所有)吗?
或者你可以试试这个>>
1.采用宽度和高度与按钮大小相同的布局(相对或线性)。
2. 现在将图像视图和文本视图放入其中。
3. 使布局可点击..
【解决方案3】:
您可以在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);
或查看this answer,它试图提供“通用”解决方案。