Search code examples
javabitmappixel

What is happening in this pixel-rendering algorithm?


I just went across some code on how to draw a pixel array on top of another pixel array that looks like this:

public class Bitmap {

private int[] pixels;
private int w, h;

public void draw(Bitmap b, int xp, int yp) {
    int x0 = xp;
    int x1 = xp+b.w;
    int y0 = yp;
    int y1 = yp+b.h;

    if(x0 < 0) x0 = 0;
    if(x1 > w) x1 = w;
    if(y0 < 0) y0 = 0;
    if(y1 > h) y1 = h;

    for (int y = y0; y < y1; y++) {
        int sp = (y - yp) * b.w - xp;
        int dp = (y) * w;

        for (int x = x0; x < x1; x++) {
            int c = b.pixels[sp + x];
            if (c < 0) pixels[dp + x] = b.pixels[sp + x];
        }
    }
}

}

As You can see, one is able to draw a Bitmap object on specific coordinates on top of another Bitmap.

The thing I don't get are the two for loops. I know, that the outer for loop is the y axis of the Bitmap drawn, and starts the inner for loop to draw the x axis of the Bitmap.

Now I came over this:

int sp = (y - yp) * b.w - xp;
int dp = (y) * w;

What exactly do sp and dp stand for? And what does 'c' mean later on in

int c = b.pixels[sp + x];
if (c < 0) pixels[dp + x] = b.pixels[sp + x];

?

Thanks in advance, best regards


Solution

  • Given the algorithm, we can guess what the original author was thinking:

    • sp is "source position": the start of the row in the source bitmap
    • dp is "destination position": the start of the row in the destination bitmap
    • c is "color": the source pixel value (where negative values are transparent).