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;

    protected void onCreate(Bundle savedInstanceState) {

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

    private void setTextColorForImage(final TextView textView, Bitmap firstPhoto) {
            .generate(new Palette.PaletteAsyncListener() {
                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);

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.


comments powered by Disqus