如何在Android中获取像素颜色

时间:2011-10-18 12:41:15

标签: android pixel

我正在使用Intent来调用并显示来自Gallery的图像,现在我可以使用以下方法在TextView中获取图像的坐标:

final TextView textView = (TextView)findViewById(R.id.textView); 
final TextView textViewCol = (TextView)findViewById(R.id.textViewColor);
targetImage.setOnTouchListener(new ImageView.OnTouchListener(){     
    @Override   
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub       
        int x=0;
        int y=0;
        textView.setText("Touch coordinates : " +       
        String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
        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);
        if(pixel == Color.RED){
               textViewCol.setText("It is RED");
            }

        /*if(redValue == 255){
            if(blueValue == 0)
                if(greenValue==0)
               textViewCol.setText("It is Red");
            }*/
        return true;    }     
    });

现在我需要做的是;获取用户选择的确切坐标的color (RGB value),然后将每个坐标分配给#FF0000#00FF00#0000FF但是现在,请帮助获取基于Pixel的颜色我所拥有的。

干杯。

3 个答案:

答案 0 :(得分:113)

您可以从视图中获取像素:

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

Color函数返回每个通道中的值。所以你要做的就是检查Red是255还是绿色和蓝色是0,而不是将textView文本设置为“它是红色”。请注意,说某些东西是红色不仅仅是红色通道大于零。当然,Cos 255-Green和255-Red是黄色的。 您还可以将像素与不同颜色进行比较。 例如:

if(pixel == Color.MAGENTA){
   textView.setText("It is Magenta");
}

希望它有所帮助。

答案 1 :(得分:3)

您可以根据需要修改此项。此代码段将帮助您获得像素颜色。

public static int getDominantColor(Bitmap bitmap) {
    Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, 1, 1, true);
    final int color = newBitmap.getPixel(0, 0);
    newBitmap.recycle();
    return color;
}

答案 2 :(得分:1)

这对我来说更准确。这里的关键是使用View.getDrawingCache代替DrawableBitmap

palleteView.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent ev) {
        // TODO Auto-generated method stub
        ImageView img = (ImageView) v;

        final int evX = (int) ev.getX();
        final int evY = (int) ev.getY();

        img.setDrawingCacheEnabled(true);
        Bitmap imgbmp = Bitmap.createBitmap(img.getDrawingCache());
        img.setDrawingCacheEnabled(false);

        try {
            int pxl = imgbmp.getPixel(evX, evY);

            pickedColorView.setBackgroundColor(pxl);

        }catch (Exception ignore){
        }
        imgbmp.recycle();

        return true;   
    }
});
相关问题