Placing text with appropriate color over image in Android

You can change the color of the TextView according to the colors of the ImageView via Palette API from the Support Library. You can extract the prominent colors from an image and set the appropriate color on an overlaid TextView.

The code in following listing shows how to use the Palette API to perform an asynchronous operation on a Bitmap and using the result to set the color on a TextView.

public class MainActivity extends AppCompatActivity {
    TextView tv;
    ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image3);

        tv = (TextView) findViewById(R.id.tv);
        iv = (ImageView) findViewById(R.id.iv);
        Bitmap bitmap = ((BitmapDrawable) iv.getDrawable()).getBitmap();
        setTextColorForImage(tv, bitmap);
    }

    private void setTextColorForImage(final TextView textView, Bitmap firstPhoto) {
        Palette.from(firstPhoto)
            .generate(new Palette.PaletteAsyncListener() {
                @Override
                public void onGenerated(Palette palette) {
                    Palette.Swatch swatch = palette.getVibrantSwatch();
                    if (swatch == null && palette.getSwatches().size() > 0) {
                        swatch = palette.getSwatches().get(0);
                    }
                    int titleTextColor = Color.WHITE;

                    if (swatch != null) {
                        titleTextColor = swatch.getTitleTextColor();
                        titleTextColor = ColorUtils.setAlphaComponent(titleTextColor, 255);
                    }
                    textView.setTextColor(titleTextColor);
                }
            });
    }
}

In the preceding method we perform an asynchronous calculation using the Palette API to get the vibrant color we want to use for the TextView. The default behavior is that the color will be translucent, and if we want to disable that we need to use ColorUtils.setAlphaComponent() to make the color opaque. Also, the prceding code has two fallbacks; if the vibrant color isn’t available we get the first swatch from the ones that are. If we still didn’t get a swatch we default to the color white.

Result

android_palette_api.png
comments powered by Disqus