Android - Get Color From ImageView with ColorFIlte

2019-06-23 22:03发布

I'm trying to get the color of an ImageView within a GridView that I've applied a color filter too previously. I'm running on a Nexus 4 with 4.2.2

I'm altering the color of the ImageView like this. The actual color of the image is white before I apply a filter.

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));

Now this doesn't actually alter the source images color which is what I want. That always remains white.

My problem is I'm trying to reference the color well after I've lost the data I used to set it. I want to long press on the ImageView and get its color.

I found some code at the below question, but it doesn't appear to work as it always returns white (255,255,255), which IS the color of the original image, but not the filter. How to Get Pixel Colour in 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);

I've tried stuff like the below, but it just crashes when I call getColorFilter.

ImageView image = (ImageView)findViewById(R.drawable.bufferbuildercolor3);
ColorFilter test = image.getColorFilter();

I'm not sure what else to do, except maybe find the X/Y of the actual grid position, and then get the screens background color at that point rather than the images. It seems like there should be an easier way to do this though?

1条回答
Rolldiameter
2楼-- · 2019-06-23 22:49

You could tag the ImageView (or any View for that matter) with the data you're interested in retrieving later on. For example, tag the view with the same Color that you use to construct the PorterDuffColorFilter:

Color tagColor = Color.rgb(Color.red(color),Color.green(color), Color.blue(color));
// tag
imageview.setTag(tagColor);

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

Obviously the tag will get garbage collected when the related view does.

Alternatively, the approach in your 3rd code snippet might actually work if you fix it up. Currently you're trying to inflate a view by looking for a drawable id - that doesn't make sense. The id should be in the form of R.id.imageview_id, i.e.:

ImageView image = (ImageView) findViewById(R.id.imageview);
ColorFilter test = image.getColorFilter();
查看更多
登录 后发表回答