获取ImageView的背景颜色。

9

我有一个普通的 ImageView 对象 colorSquare

通过调用以下方式设置对象颜色非常简单。

colorSquare.setBackgroundColor(color);

但是如何实现反向操作,即获取ImageView背景的颜色呢?

2个回答

18
你可以做的是,从ImageView中获取ColorDrawable。
ColorDrawable drawable = (ColorDrawable) colorSquare.getBackground();

现在

drawable.getColor()

将会给你颜色。

只有当您设置了颜色时,它才能正常工作,否则您将会得到一个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;

}

其中 x 和 y 分别是 ImageView 触摸事件的 event.getX() 和 event.getY()。


2
这个回复跟问题有什么关系? - swooby

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