如何在将在 RemoteView 中使用的可绘制对象上设置滤色器?

cas*_*orz 6 android android-widget android-notifications remoteview android-remoteview

我有一个必须应用过滤器的ImaveViewon a 。RemoteView当我不在的时候,RemoteView这就是我所做的,而且效果很好:

    Drawable icon = getResources().getDrawable(R.drawable.icon);
    icon.setColorFilter(color, PorterDuff.Mode.SRC_IN);
    image.setImageDrawable(icon);
Run Code Online (Sandbox Code Playgroud)

似乎RemoteView没有办法让我设置不是资源的可绘制对象。我该怎么做呢?

谢谢。

Jay*_* PM 9

下面的代码适用于 RemoteViews,它是主屏幕小部件中的 ImageView,用于更改色调颜色。在运行 API 级别 29 的设备上进行测试

remoteViews.setInt(R.id.myRemoteViewId, "setColorFilter", Color.parseColor("#000000"))
Run Code Online (Sandbox Code Playgroud)


Ark*_*ski 1

我有类似的问题。对我来说,解决方案是使用位图。这两种方法应该会给你答案或至少某种解决方案。

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;
}
Run Code Online (Sandbox Code Playgroud)

R.id.iv_icon - 是布局中 ImageView 的 id

您始终可以从 ImageView 获取可绘制对象并将其转换为位图。