将png转换为drawable,然后是colorfilter,然后是bitmap - 无法正常工作

我有一个由白色和灰色(均为alpha 100%)和完全透明区域(alpha == 0)组成的png . 我试图用不同的颜色着色图标,然后返回一个位图 . 这是我的代码 .

Drawable iconDrawable = getResources().getDrawable(iconDrawableId);
        iconDrawable.mutate().setColorFilter(0xffff00ff, PorterDuff.Mode.MULTIPLY);
        Bitmap outputBmp = ((BitmapDrawable) iconDrawable).getBitmap();

不幸的是我的图标保持白色和灰色 . 我在监督什么?

回答(1)

2 years ago

在迈克斯提示之后,我意识到我可以这样做:

Drawable iconDrawable = getResources().getDrawable(iconDrawableId);
        iconDrawable.mutate().setColorFilter(0xffffff00, PorterDuff.Mode.MULTIPLY);
        Bitmap bitmap = Bitmap.createBitmap(iconDrawable.getIntrinsicWidth(), iconDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        iconDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        iconDrawable.draw(canvas);

但最后我还是去了

Bitmap whiteBmp = BitmapFactory.decodeResource(getResources(), iconDrawableId);
        Paint paint = new Paint();
        paint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY));
        Bitmap bitmapResult = Bitmap.createBitmap(whiteBmp.getWidth(), whiteBmp.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapResult);
        canvas.drawBitmap(whiteBmp, 0, 0, paint);