Mindril
Mindril

Reputation: 679

How do I create a 2 dimensional color gradient in android

I'm designing a simple paint program and I need to make a color picker view for users to select background and paintbrush colors. I thought the best approach would be to split the rgb component of the color int in two and add them across a rectangle with vertical pixels being the 'rb' part and horizontal ones as the 'bg' part. For example: green - ff00ff00 would be broken into 00f and f00 and then added and OR'd with ff000000 to preserve the alpha. Maybe I'm doing the math wrong because I get a series of squares instead of a continuous gradient. Here is the relevant code:

    int width = 500, height = 500;
    int color = 0, xColor = 0, yColor = 0, MAX_HALF = 0xfff;
    bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
    for(int x = 0; x < width; x++){
        for(int y = 0; y < height; y++){
            xColor = x * MAX_HALF / width;
            yColor = (y * MAX_HALF / height) << 12;
            color = xColor | yColor | 0xff000000;
            bitmap.setPixel(x,y,color);
        }
    }
    canvas.drawBitmap(bitmap,0,0,null);

This is the image I get.enter image description here

Is it the code or the math?

Upvotes: 0

Views: 327

Answers (1)

Sreejesh K Nair
Sreejesh K Nair

Reputation: 603

There are two main ways you can accomplish that with a drawable:

Use two linear gradients Use two radial gradients

check this link

Android: How to draw a two dimensional gradient

Upvotes: 1

Related Questions