繁体   English   中英

如何在Android中获取像素颜色

[英]How to Get Pixel Color in Android

我正在使用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颜色。

干杯。

您可以从视图中获取像素,如下所示:

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文本设置为“ it is red”。 只需注意说某物为红色并不仅仅意味着红色通道大于零。 'Cos 255-绿色和255-红色是黄色。 您也可以将像素与其他颜色进行比较。 例如:

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

希望能帮助到你。

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

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

这对我来说更准确。 这里的关键是使用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;   
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM