Android的 - 按钮,图像 - 当按钮被禁用的模糊图像 [英] Android - button with image - dim image when button disabled

查看:136
本文介绍了Android的 - 按钮,图像 - 当按钮被禁用的模糊图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android中,我有一个包含一个图像和文本的按钮。当按钮被禁用,则文本会自动显示为灰色,但图像保持不变。是否有可能有图像变暗,当按钮被禁用,而无需两个单独的图像?

In Android, I have a button that contains an image and text. When the button is disabled, the text is automatically grayed out, but the image stays the same. Is it possible to have the image dimmed when the button is disabled without having two separate images?

推荐答案

终于拿到了!

我还没有找到一种方法,通过XML设置图像要做到这一点,所以必须将其设置在code。下面是我的作品:

I haven't found a way to do this by setting the image in XML, so have to set it in the code. Here's what I got that works:

Button btnObjects = (Button)this.findViewById(R.id.button_objects);
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.button_image_objects);
if( <button needs to be disabled> )
{
    btnObjects.setEnabled(false);
    bm = adjustOpacity(bm, 128);
}
else
{
    btnObjects.setEnabled(true);
}
btnObjects.setCompoundDrawablesWithIntrinsicBounds(null, new BitmapDrawable(bm), null, null);

//and here's where the magic happens
private Bitmap adjustOpacity(Bitmap bitmap, int opacity)
{
    //make sure bitmap is mutable (copy of needed)
    Bitmap mutableBitmap = bitmap.isMutable()
                           ? bitmap
                           : bitmap.copy(Bitmap.Config.ARGB_8888, true);

    //draw the bitmap into a canvas
    Canvas canvas = new Canvas(mutableBitmap);

    //create a color with the specified opacity
    int colour = (opacity & 0xFF) << 24;

    //draw the colour over the bitmap using PorterDuff mode DST_IN
    canvas.drawColor(colour, PorterDuff.Mode.DST_IN);

    //now return the adjusted bitmap
    return mutableBitmap;
}

这篇关于Android的 - 按钮,图像 - 当按钮被禁用的模糊图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆