有没有一种方法可以使 Android 中的 ImageButton 变灰,而无需维护原始图像的单独灰色副本?

Is there a way I can gray out an ImageButton in Android without maintaining a separate gray copy of the original Image?

我正在尝试制作一个 ImageButton 最初具有灰色效果 并在选择时变成其 原始颜色.我正在努力实现类似 的目标。我知道这可以在 CSS 中完成,但想知道是否存在与其等效的任何 Android 属性/函数。

我读到 post here 似乎建议我必须维护同一图像的不同灰色副本才能实现此目的。但是如果我有的话,维护同一个图像的 2 个副本会消耗大量内存,比如说 100+ ImageButtons。

Unlike a regular Button, an ImageButton or a Button that has an image background is not grayed when disabled. You actually have to use another image or to process it in a way it appears grayed.

那么在Android中真的没有办法实现在CSS中使用灰度可以实现的东西吗?

感谢您的宝贵时间!

如果您使用 .png 图像,您可以使用 ImageView 颜色过滤器属性。

public void setDisabled(ImageView imageView) {
    final ColorMatrix grayscaleMatrix = new ColorMatrix();
    grayscaleMatrix.setSaturation(0);
    imageView.setColorFilter(new ColorMatrixColorFilter(grayscaleMatrix));
}

我知道我可能会很晚,但还有另一种选择 - 我遇到了同样的情况,我试图解决它并找到了一些简单的替代方案。

我用过的ImageButton专用setAlpha(floatValue);

示例:

private ImageButton btnPlay;
[...]
btnPlay.setAlpha(0.5f);

另一种为 ImageView 设置 Alpha 效果的方法(从技术上讲也适用于扩展 ImageView 的 ImageButton)是 setImageAlpha(inValue between 0 and 255) - 但对我来说它对 ImageButton 也不起作用。


这种方法的一个缺点可能是它不是真正的“灰化”。通过设置透明度,如果按钮后面的背景是纹理或图像,您可能会面临风险。此解决方案最适合纯色背景,如黑色、深色、白色、灰色等,这也有助于营造“灰色”感觉。

感谢您的评论帮助我们解决了这个问题。