有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法重新缩放可绘图按钮

private float iconScale = 0.05f;    
// Set size of drawables in buttons
Drawable drawable = getResources().getDrawable(R.drawable.cutlerywhite);
drawable.setBounds(0, 0, (int)(drawable.getIntrinsicWidth()),
        (int)(drawable.getIntrinsicHeight()));
ScaleDrawable sd = new ScaleDrawable(drawable, 0, iconScale, iconScale);

fnbButton.setCompoundDrawables(sd, null, null, null); //set drawableLeft for example

我正在尝试缩小一个可在Button中使用的绘图。现在,我的按钮中没有显示任何内容:

enter image description here

左边应该有一个抽屉。 这里有什么问题?我所做的和我在这里看到的不同答案中看到的完全一样

XML:

<Button
    安卓:id="@+id/fnbButton"
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content"
    安卓:background="@drawable/rounded_button_blue"
    安卓:padding="5dp"
    安卓:text="@string/fnb_button"
    安卓:textAllCaps="false"
    安卓:textColor="@color/white"
    app:layout_constraintBaseline_toBaselineOf="@id/otherButton"
    app:layout_constraintEnd_toEndOf="parent" />

共 (3) 个答案

  1. # 1 楼答案

    试试这个

    Drawable drawable = getResources().getDrawable(R.drawable.cutlerywhite);
    ScaleDrawable sd = new ScaleDrawable(drawable, Gravity.CENTER, iconScale, iconScale);
    Drawable d1 = sd.getDrawable();
    d1.setLevel(1);
    sd.setLevel(1);
    fnbButton.setCompoundDrawablesWithIntrinsicBounds(sd, null, null, null);
    
  2. # 2 楼答案

    也许这个选择会有所帮助

       private void useScaledDrawableLeft(Button buttonView, float scale, @DrawableRes int imageResource) {
            Resources res = getResources();
            BitmapDrawable bd = (BitmapDrawable) res.getDrawable(imageResource);
            Bitmap b = Bitmap.createScaledBitmap(bd.getBitmap(),
                    (int) (bd.getIntrinsicHeight() * scale),
                    (int) (bd.getIntrinsicWidth() * scale),
                    false);
    
            BitmapDrawable scaleDrawable = new BitmapDrawable(b);
            buttonView.setCompoundDrawablesWithIntrinsicBounds(scaleDrawable, null, null, null);
    }
    
  3. # 3 楼答案

    我最终做到了:

    Drawable drawableFnb = getResources().getDrawable(R.drawable.cutlerywhite);
    Drawable drawableSunbed = getResources().getDrawable(R.drawable.logowhite);
    
    ScaleDrawable sdFnb = new ScaleDrawable(drawableFnb, Gravity.LEFT, 1, 1);
    ScaleDrawable sdSunbed = new ScaleDrawable(drawableSunbed, Gravity.LEFT, 1, 1);
    Drawable d1 = sdFnb.getDrawable();
    Drawable d2 = sdSunbed.getDrawable();
    
    Dims fnbDims = getIconDims(drawableFnb);
    Dims sunbedDims = getIconDims(drawableSunbed);
    
    d1.setBounds(0, 0, fnbDims.getWidth(), fnbDims.getHeight());
    d2.setBounds(0, 0, sunbedDims.getWidth(), sunbedDims.getHeight());
    
    fnbButton.setCompoundDrawables(d1, null, null, null);
    sunbedButton.setCompoundDrawables(d2, null, null, null);