原創文章,如有轉載,請注明出處: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))
雖然還是讓設計切圖來得友善,但是掌握一些基本的技巧還是很有必要的
歡迎關注我的公衆号,和我一起每天進步一點點!
