【问题标题】:How can I compare the Image of an ImageButton to a drawable?如何将 ImageButton 的图像与可绘制对象进行比较?
【发布时间】:2021-05-15 04:38:20
【问题描述】:

如果我的 ImageButton button 的图像等于可绘制对象,我希望执行某个操作。像这样:

if (button.getBackground().getConstantState()==getResources().getDrawable(R.drawable.mydrawable).getConstantState())
{
     //perform action//
}

但如果我这样做,getDrawable 会出现红色下划线,我不知道为什么?

谁能帮帮我?

【问题讨论】:

  • 肯定有一些逻辑将你的按钮设置为这个值,对吧?为什么不在那里添加检查而不是检查附加了哪些资源?
  • 支票是什么意思?我有一个 ImageButton,其图像可以由用户选择。如果在该 ImageButton 上选择了某个图像,我想要一个特定操作,该操作仅在设置该图像时才会发生...
  • 因此,当用户选择图像时,只需使用自定义变量来保留他选择的图像,并将您需要的内容与此变量进行比较。比比较 drawable 要好得多。
  • 其实更好,谢谢

标签: java android imageview android-drawable imagebutton


【解决方案1】:

第一

ImageButton temp =  findViewById(R.id.myImagebtn);
Bitmap imageBtm = ((BitmapDrawable)temp.getDrawable()).getBitmap();
Drawable myDrawable = getResources().getDrawable(R.drawable.apple);
Bitmap appleBtm = ((BitmapDrawable) myDrawable).getBitmap();

if(imageBtm.sameAs(appleBtm))
{
Log.i("Bitmap compare", "equal");
}

【讨论】:

    【解决方案2】:

    getConstantState() 并不总是有效。

    你可以比较它们是否相等:

    • 宽x高
    • 像素
    • 字节

    【讨论】:

    • 不幸的是,我只有大小相同的图片,无论是像素还是字节。我没有其他功能可以使用吗?不知何故,必须可以比较 id 或类似的东西......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多