天天看点

Android 代码改变图标颜色及动态生成Drawerable Selector

原创文章,如有转载,请注明出处:http://blog.csdn.net/myth13141314/article/details/64906237

Android 开发中Drawerable的Selector文件用得很频繁,有时候图标文件只有默认的,缺少选中状态或是按下状态的图标资源,这个时候就需要用代码改变图标的颜色,动态生成Selector文件

改变图标的颜色

主要就是改变画笔的颜色重新绘制

/*
* change image color
* @params context
* @params resId, the image resource need to change color
* @params color, target color, default is white
* 
* @return bitmap
*
* */
public static Bitmap changeImageColor(Context context, int resId, int color) {
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId);

        Bitmap mAlphaBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(mAlphaBitmap);
        Paint mPaint = new Paint();
        if (color != ) {
            mPaint.setColor(color);
        }else {
            mPaint.setColor(Color.parseColor("#FFFFFF"));
        }
        Bitmap alphaBitmap = bitmap.extractAlpha();
        mCanvas.drawBitmap(alphaBitmap, , , mPaint);

        return mAlphaBitmap;
    }
           

将Bitmap转化为Drawerable

new BitmapDrawable(context.getResources(), bitmap)
           

生成Selector文件

/*
* 生成selector
* 
* */
public static StateListDrawable initSelector(Context context, int normal) {
    StateListDrawable states = new StateListDrawable();

    //按下状态
    states.addState(new int[] {android.R.attr.state_pressed},
            new BitmapDrawable(context.getResources(), changeImageColor(context, normal, Color.parseColor("#eb3636"))));

    //选中状态
    states.addState(new int[] {android.R.attr.state_selected},
            new BitmapDrawable(context.getResources(), changeImageColor(context, normal, Color.parseColor("#eb3636"))));

    if (Build.VERSION.SDK_INT > LOLLIPOP) {
        states.addState(new int[] {}, context.getResources().getDrawable(normal, null));
    }else {
        states.addState(new int[] {}, context.getResources().getDrawable(normal));
    }

    return states;
}
           

应用

imageView.setImageDrawable(initSelector(context, R.mipmap.icon))
           

虽然还是让设计切图来得方便,但是掌握一些基本的技巧还是很有必要的

欢迎关注我的公众号,和我一起每天进步一点点!

Android 代码改变图标颜色及动态生成Drawerable Selector