How do I set a color filter on a drawable which will be used in a RemoteView?
Asked Answered
W

2

6

I have an ImaveView on a RemoteView for which I have to apply a filter. When not in the RemoteView this is what I do and it works well:

    Drawable icon = getResources().getDrawable(R.drawable.icon);
    icon.setColorFilter(color, PorterDuff.Mode.SRC_IN);
    image.setImageDrawable(icon);

The RemoteView does not appear to have a method for me to set a drawable that is not a resource. How would I go about doing this?

Thanks.

Waiwaif answered 1/7, 2015 at 18:23 Comment(0)
T
10

Below code worked for RemoteViews which is ImageView in Home screen widget for changing tint color. Tested on device running with API Level 29

remoteViews.setInt(R.id.myRemoteViewId, "setColorFilter", Color.parseColor("#000000"))
Tropical answered 22/5, 2021 at 7:7 Comment(1)
Which Color class are you importing?Warn
L
1

I had similar problem. For me the solution was to use the bitmap. These two methods should give you the answer or at least some kind of solution.

private void setCurrentStatus(Context context, RemoteViews remoteViews) {
    Bitmap source = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
    Bitmap result = changeBitmapColor(source, Color.YELLOW);

    remoteViews.setBitmap(R.id.iv_icon, "setImageBitmap", result);
}

private Bitmap changeBitmapColor(Bitmap sourceBitmap, int color) {
    Bitmap resultBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0,
            sourceBitmap.getWidth() - 1, sourceBitmap.getHeight() - 1);
    Paint p = new Paint();
    ColorFilter filter = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN);
    p.setColorFilter(filter);

    Canvas canvas = new Canvas(resultBitmap);
    canvas.drawBitmap(resultBitmap, 0, 0, p);

    return resultBitmap;
}

R.id.iv_icon - is the id of the ImageView from the layout

You can always get drawable from your ImageView and convert it to bitmap.

Ladylike answered 7/10, 2015 at 10:21 Comment(1)
Is there also a "tint" solution, including in XML ?Jaggy

© 2022 - 2024 — McMap. All rights reserved.