Вы можете вызвать setBounds
на «составных» чертежах, чтобы изменить размер изображения.
Попробуйте этот код для автоматического изменения размера вашей кнопки:
DroidUtils.scaleButtonDrawables((Button) findViewById(R.id.ButtonTest), 1.0);
, определенной этой функцией:
public final class DroidUtils {
/** scale the Drawables of a button to "fit"
* For left and right drawables: height is scaled
* eg. with fitFactor 1 the image has max. the height of the button.
* For top and bottom drawables: width is scaled:
* With fitFactor 0.9 the image has max. 90% of the width of the button
* */
public static void scaleButtonDrawables(Button btn, double fitFactor) {
Drawable[] drawables = btn.getCompoundDrawables();
for (int i = 0; i < drawables.length; i++) {
if (drawables[i] != null) {
int imgWidth = drawables[i].getIntrinsicWidth();
int imgHeight = drawables[i].getIntrinsicHeight();
if ((imgHeight > 0) && (imgWidth > 0)) { //might be -1
float scale;
if ((i == 0) || (i == 2)) { //left or right -> scale height
scale = (float) (btn.getHeight() * fitFactor) / imgHeight;
} else { //top or bottom -> scale width
scale = (float) (btn.getWidth() * fitFactor) / imgWidth;
}
if (scale < 1.0) {
Rect rect = drawables[i].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;
drawables[i].setBounds(rect);
}
}
}
}
}
}
Имейте в виду, что это не может быть вызвано вonCreate()
действия, потому что высота и ширина кнопки там (пока) недоступны.Вызовите это на onWindowFocusChanged()
или используйте это решение для вызова функции.
Отредактировано:
Первое воплощение этой функции не работало правильно.Он использовал код userSeven7s для масштабирования изображения, но возвращение ScaleDrawable.getDrawable()
, похоже, не работает (и не возвращает ScaleDrawable
) для меня.
В измененном коде используется setBounds
предоставить границы для изображения.Android вписывает изображение в эти границы.