gpt4 book ai didi

java - 如何以编程方式使图像适合 ImageButton

转载 作者:行者123 更新时间:2023-11-30 02:20:37 25 4
gpt4 key购买 nike

我正在尝试使用此图像设置 ImageButton 的背景:enter image description here

和代码:

创建时:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

LightImageButton lightImageButton = new LightImageButton(false, getApplicationContext());
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setBackground(getResources().getDrawable(lightImageButton.getCurrentImage()));
imageButton.setOnClickListener(lightImageButton);

}

辅助类:

public class LightImageButton implements View.OnClickListener {
private static final int bulbOnImg = R.drawable.bulb_on;
private static final int bulbOffImg = R.drawable.bulb_off;
private boolean state;
private Context context;
private int currentImage;

public LightImageButton(boolean state, Context context) {
this.state = state;
this.context = context;
currentImage = bulbOffImg;
}

public int getCurrentImage() {
return currentImage;
}

@Override
public void onClick(View v) {
ImageButton btn = (ImageButton) v;

if (state) {
currentImage = bulbOnImg;
} else {
currentImage = bulbOffImg;
}
state = !state;
btn.setBackground(context.getResources().getDrawable(currentImage));
}
}

但收到下一个结果: enter image description here

我想要正确缩放的图像。我该怎么做?也许有更好的方法使用其他一些可点击的类而不是 ImageButton 来做到这一点?

最佳答案

改变这个:

imageButton.setBackground(getResources().getDrawable(lightImageButton.getCurrentImage()));

与:

imageButton.setImageResource(R.drawable.your_bulb);
imageButton.setScaleType(ImageView.ScaleType.CENTER_CROP);

enter image description here

关于java - 如何以编程方式使图像适合 ImageButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28594100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com