Android - 从应用了ColorFilter的Drawable中获取ImageView的颜色

7
我正在尝试获取一个GridView中ImageView的颜色,该ImageView之前已应用颜色过滤器。我使用的是安装有4.2.2版本的Nexus 4。
我按以下方式更改ImageView的颜色。在应用过滤器之前,图像的实际颜色为白色。
Drawable myIcon = getResources().getDrawable(R.drawable.bufferbuildercolor3);                       
myIcon.setColorFilter(new PorterDuffColorFilter(Color.rgb(Color.red(color),Color.green(color), Color.blue(color)),PorterDuff.Mode.MULTIPLY));

现在这并不会改变源图像的颜色,这正是我想要的。那个总是保持白色。
我的问题是,我试图在失去设置它的数据后引用颜色。我想长按ImageView并获取其颜色。
我在下面的问题中找到了一些代码,但它似乎不起作用,因为它总是返回白色(255,255,255),这是原始图像的颜色,而不是滤镜。 如何在Android中获取像素颜色?
ImageView imageView = ((ImageView)v);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y);

int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);

我已经尝试了以下方法,但在调用getColorFilter时会崩溃。
ImageView image = (ImageView)findViewById(R.drawable.bufferbuildercolor3);
ColorFilter test = image.getColorFilter();

我不确定还有什么其他办法,除非找到实际网格位置的X/Y坐标,然后获取该点屏幕背景颜色而不是图片。不过似乎应该有更简单的方法吧?

1个回答

7
你可以给ImageView或者任何其他的View)打上标记,以便稍后检索所需的数据。例如,使用与构造PorterDuffColorFilter相同的Color来为视图打上标记:
Color tagColor = Color.rgb(Color.red(color),Color.green(color), Color.blue(color));
// tag
imageview.setTag(tagColor);

// get tag
tagColor = (Color) imageview.getTag();

显然,当相关视图被垃圾回收时,标签也会被回收。
或者,如果你修复了第三个代码片段中的问题,那么这种方法实际上可能有效。目前,你正在尝试通过查找一个 drawable id 来填充一个视图 - 这是没有意义的。id 应该采用 R.id.imageview_id 的形式,即:
ImageView image = (ImageView) findViewById(R.id.imageview);
ColorFilter test = image.getColorFilter();

我找到了获取imageView [ImageView imageView =(ImageView)gridview.getChildAt(x)];的方法,然后能够使用您建议的标记方法。我无法从getColorFilter方法中获得任何有用的东西,但稍后我会再看一眼。这是一个额外的步骤来标记事物,但它有效!谢谢!! - Ben987654
这是一个非常棒的解决方案。我用它来通过数据绑定将颜色滤镜应用到回收视图项上。如果颜色滤镜已经被应用,那么就不需要再设置它,因此将其标记为颜色意味着只有在必要时才会应用它。 - Daniel Wilson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接