以编程方式设置可绘制大小

2022-08-31 10:13:37

图像(图标)的大小大致相同,但我需要调整它们的大小以使按钮保持相同的高度。

我该怎么做?

Button button = new Button(this);
button.setText(apiEventObject.getTitle());
button.setOnClickListener(listener);

/*
 * set clickable id of button to actual event id
 */
int id = Integer.parseInt(apiEventObject.getId());
button.setId(id);

button.setLayoutParams(new LayoutParams(
        android.view.ViewGroup.LayoutParams.FILL_PARENT,
        android.view.ViewGroup.LayoutParams.WRAP_CONTENT));

Drawable drawable = LoadImageFromWebOperations(apiSizeObject.getSmall());
//?resize drawable here? drawable.setBounds(50, 50, 50, 50);
button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);

答案 1

该方法不适用于每种类型的容器(但是,对于我的一些容器确实有效)。setBounds()ImageView

请尝试以下方法来缩放可绘制对象本身:

// Read your drawable from somewhere
Drawable dr = getResources().getDrawable(R.drawable.somedrawable);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
// Scale it to 50 x 50
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50, 50, true));
// Set your new, scaled drawable "d"

答案 2

使用 指定大小,即 50x50 大小使用setBounds()

drawable.setBounds(0, 0, 50, 50);

公共 void setBounds (int left, int top, int right, int bottom)


推荐