Getting the background color of an ImageView

末鹿安然 提交于 2020-01-20 05:00:28

问题


I have a plain ImageView object colorSquare.

It is straightforward to set the color of the object by calling.

colorSquare.setBackgroundColor(color);

But how do I do the reverse, i.e. retrieve the color of the ImageView background?


回答1:


What u can do is

get ColorDrawable from ImageView.

ColorDrawable drawable = (ColorDrawable) colorSquare.getBackground();

now

drawable.getColor()

will give u the Color.

This will work only if u have set the Color or else u will get ClassCastException




回答2:


private int colorfindcolor(View v, int x, int y) {


    int offset = 1; // 3x3 Matrix
    int pixelsNumber = 0;

    int xImage = 0;
    int yImage = 0;


    Bitmap imageBitmap = BitmapFactory.decodeResource(context.getResources(),
            R.drawable.palette_color);
    xImage = (int) (x * ((double) imageBitmap.getWidth() / (double) paletteImg
            .getWidth()));
    yImage = (int) (y * ((double) imageBitmap.getHeight() / (double) paletteImg
            .getHeight()));

    for (int i = xImage - offset; i <= xImage + offset; i++) {
        for (int j = yImage - offset; j <= yImage + offset; j++) {
            try {

                color = imageBitmap.getPixel(i, j);

                pixelsNumber += 1;
            } catch (Exception e) {
                // Log.w(TAG, "Error picking color!");
            }
        }
    }

    return color;

}

Where x,y are event.getX(),event.getX() of imageview touch event



来源:https://stackoverflow.com/questions/9339542/getting-the-background-color-of-an-imageview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!