views:

46

answers:

2

I use the following code with the intention to create an image that's half white and half black and put it on a button. What's wrong with my code? (latter we want to use a more complicated logic about what pixels are white and what are black but it should still be black and white)

int height = 100;
int width = 100;

quadratImage = Bitmap.createBitmap(
        width, 
        height, 
        Bitmap.Config.ALPHA_8);
for (int x = 0; x < width; x++){
    for (int y = 0; y < height; y++){
        int color;

        if (x< 50){

            color = R.color.black;

        }
        else{
            color = R.color.white;
        }

        quadratImage.setPixel(
                x, y, color);
    }
}
quadratImage.prepareToDraw();
imageButton.setImageBitmap(quadratImage);

My colors are defined as:

<color name="black">#000000</color>
<color name="white">#ffffff</color>
+1  A: 

If you want an image split into 4 it won't work, you'll get it split in two - half black, half white.

You need to put a test inside the if (x<50) (and the other condition) braces to vary the colour according to the y value.

OK, your comment noted, you need

Resources res = this.getResources();

somewhere above,then

color = res.getColor(R.color.black);

and for white

NickT
This doesn't produce a image that's half white half black. If it would it would be trival to add an y condition.
Christian
+1  A: 

For one thing, when you're drawing straight to a Bitmap the int for a color isn't the resource ID of a color, but the hex representation of the ARGB actual color value (eg 0xff000000 for black, 0xffffffff for white). You can also get this value via getResources().getColor(colorResourceId).

Also, instead of trying to draw straight to the bitmap pixel by pixel, learn to use Android's Canvas tools - you could simply fill the canvas with white, then drawRect (http://developer.android.com/reference/android/graphics/Canvas.html#drawRect(float, float, float, float, android.graphics.Paint)) a black rectangle to the other half of the screen. It would be a lot less code than your nested loops, and the system can optimize the canvas painting there with hardware acceleration and other shortcuts rather than painfully forming the entire bitmap pixel by pixel.

Yoni Samlan