6

我有一个带有文本的按钮,左侧有一个drawable。有什么办法可以使可绘制的比例达到适当的大小(填充按钮的高度),同时保持其纵横比?

我的布局的相关摘录:

        <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"/>  
4

3 回答 3

2

您可以根据按钮的尺寸调整图像的大小,使用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;

}

现在为您的按钮使用这个调整大小的图像。 参考

于 2012-05-21T09:59:38.057 回答
0

你可以在图形中创建一个按钮(包含所有)吗?

或者你可以试试这个>> 1.采用宽度和高度与按钮大小相同的布局(相对或线性)。2. 现在将图像视图和文本视图放入其中。3.使布局可点击..

于 2012-05-21T09:52:21.193 回答
0

您可以在以下代码中使用由以下代码组成的函数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);

或者看看这个答案,它试图给出一个“通用”的解决方案。

于 2015-09-09T20:26:22.603 回答