android changing color of image from left to right smoothly

418 views Asked by At

I want to change the color of an image from left to right like a spectrum and see the change of color as it's changing, here is my code, the problem is that it change from the original image to the final image after a click on buttom, but I don't know how to change it so I can see the change as it's changing.

final ImageView imgView = (ImageView) findViewById(R.id.imageView);
    Button btn = (Button) findViewById(R.id.button1);

    Bitmap bitmap = ((BitmapDrawable) imgView.getDrawable()).getBitmap();
    final Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {


            for( x = 0; x < mutableBitmap.getWidth() ; x++){
                runOnUiThread (new Thread(new Runnable() { 
                     public void run() {
                         try {
                                        for(int y = 0; y < mutableBitmap.getHeight() ; y++){
                                            int c = mutableBitmap.getPixel(x, y);
                                            mutableBitmap.setPixel(x, y, Color.rgb(Color.red(c), (200 - Color.green(c)), Color.blue(c)));
                                            Log.d("IMAGE", ""+x);
                                        }   
                                        imgView.setImageBitmap(mutableBitmap);
                                            Thread.sleep(100);
                                        } catch (InterruptedException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                             }

                }));
            }
        }


    });
2

There are 2 answers

0
Johnson On BEST ANSWER

You can right click on your drawable folder, select New\Drawable resource file. Choose a name for the file and click OK. After that you can add this code:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
    android:angle="135"
    android:centerColor="@color/colorAccent"
    android:endColor="@color/colorPrimaryDark"
    android:startColor="@color/colorPrimary"
    android:type="linear" />

You can create new colors from you color.xml and use them. Then in the java code:

imageView.setImageDrawable(getResources().getDrawable(R.drawable.YOURDRAWABLENAME));
4
Johnson On

I'm not an expert, but I think you can try this to choose the colors you want:

int[] colors = {0xFFFFFFFF, 0xFFFF0000, 0xFF00FF00}

And this to apply them:

mutableBitmap.setPixel(x, y, new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, colors);

Hope it helps