Search code examples
androidcolorsbackground-image

Get imageView color and set complementary color


I make Viewpager and there is only ImageView.

that images from server. So it can be bright or dark.

and there is Layout for notice current page / totalPage like this.

enter image description here

Now I want to make if Image is bright, notice layout make dark.

and if Image is dark, notice layout make bright.

So. My Question is

  1. How can I know current image is bright or dark?
  2. And How I can make complementary color from image?

Solution

  • The Android Support Library r21 and above includes the Palette class, which lets you extract prominent colors from an image. To extract these colors, pass a Bitmap object to the Palette.generate() static method in the background thread where you load your images. If you can't use that thread, call the Palette.generateAsync() method and provide a listener instead.

    To use the Palette class in your project, add the following Gradle dependency to your app's module:

    implementation 'androidx.palette:palette:$version'
    

    To get the color from image:

        Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
            public void onGenerated(Palette palette) {
                // Do something with colors...
            }
    });
    

    The palette library attempts to extract the following six color profiles:

    Light Vibrant, Vibrant, Dark Vibrant, Light Muted, Muted and Dark Muted.

    Finding complementary color is very simple in RGB model. For any given color, for example, red (#FF0000) you need to find the color, which, after being added to red, creates white (0xFFFFFF). Naturally, all you need to do, is subtract red from white and get cyan (0xFFFFFF - 0xFF0000 = 0x00FFFF).