Search code examples
androidpixel

Is there a way to directly access the color of a pixel of the display in Android?


Do you know if there is a way to get, at some point during the execution of an application, an information of the colors of all the pixels (or one pixel, it's indifferent)? The thing I need to get the average color of the entire display at a particular instant. I only found solutions that use screenshots of the display, but this thing takes time for the computation. Practically, even if there is, I would do something like:

Display display = ((WindowManager)getSystemService(this.WINDOW_SERVICE)).getDefaultDisplay();
int pixel = display.getPixel(x,y);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);

Solution

  • You can get your root view as a bitmap and then sample pixels.

    For example:

    View myLayout = findViewById(R.id.myRootLayout);
    myLayout.setDrawingCacheEnabled(true);
    Bitmap bitmap = myLayout.getDrawingCache();
    myLayout.setDrawingCacheEnabled(false);
    
    //sample a pixel
    int color = bitmap.getPixel(20,20);