android - 非透明像素上的 ImageView 颜色过滤器。夹子

标签 android image mask clip

我有一个带有位图的 ImageView。此位图具有 alpha channel 和透明像素。 当我尝试将 ColorFiter 与 Mode.OVERLAY(自蜂窝)一起使用时 - 提供颜色覆盖整个 ImageView (整个矩形),但我只想覆盖非透明像素。我如何裁剪 imageview 的 Canvas 以在我想要的地方执行过滤器?

已更新

我在 png 中有灰色图像:

enter image description here

当我尝试使用 MODE_ATOP 时,我得到:

enter image description here

当我使用 OVERLAY 时,我得到:

enter image description here

以及我想要得到的:

enter image description here

最佳答案

可能有更有效的方法来做到这一点(可能通过创建一个 ColorMatrixColorFilter 来近似它),但由于 Mode.OVERLAY 似乎是 hard to simplify otherwise ,这里有一些示例代码应该实现你想要的:

public class MyActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final ImageView imageView = new ImageView(this);
        setContentView(imageView);

        final Paint paint = new Paint();
        Canvas c;

        final Bitmap src = BitmapFactory.decodeResource(getResources(),
                android.R.drawable.sym_def_app_icon);
        final int overlayColor = Color.RED;

        final Bitmap bm1 = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888);
        c = new Canvas(bm1);
        paint.setColorFilter(new PorterDuffColorFilter(overlayColor, PorterDuff.Mode.OVERLAY));
        c.drawBitmap(src, 0, 0, paint);

        final Bitmap bm2 = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Config.ARGB_8888);
        c = new Canvas(bm2);
        paint.setColorFilter(new PorterDuffColorFilter(overlayColor, PorterDuff.Mode.SRC_ATOP));
        c.drawBitmap(src, 0, 0, paint);

        paint.setColorFilter(null);
        paint.setXfermode(new AvoidXfermode(overlayColor, 0, Mode.TARGET));
        c.drawBitmap(bm1, 0, 0, paint);

        imageView.setImageBitmap(bm2);
    }

}

简而言之,我们使用OVERLAY模式绘制源位图和颜色,然后使用辅助位图(使用SRC_ATOP模式合成),我们使用AvoidXfermode组合它不绘制透明像素。

原图:

original image

结果:

result

关于android - 非透明像素上的 ImageView 颜色过滤器。夹子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11968040/

相关文章:

linux - 创建 iso 格式的操作系统镜像

html - CSS悬停在特定位置显示文本

image - 查找相似字符串的索引策略

html - 是否可以动态屏蔽/裁剪 html 元素组?

python - 将 nan 值从一个数据框复制到另一个数据框

java - 在 ArrayList 线程安全上移动对象的最佳方法是什么?

Android小部件背景没有出现,没有响应

java - java中当语句为真时if循环代码不执行

android - 能否禁用/调整 Fresco 对大图像(>2048 像素)的自动调整大小?

html - Masking SVG-filter,不是简单地将mask和filter结合起来