Typically, one could iterate over an array of images from top to bottom in rows and inside each row from left to right above the columns. In this case, you want the opposite: we want to iterate over each column, starting from the left, and inside the column we look through all the rows and check for the presence of a black pixel.
This will give you the leftmost black pixel:
size_t maxIndex = height * bytesPerRow; for (size_t x = 0; x < bytesPerRow; x += bytesPerPixel) { for (size_t index = x; index < maxIndex; index += bytesPerRow) { if (rawData[index + 3] > 0) { goto exitLoop; } } } exitLoop: if (x < bytesPerRow) { x /= bytesPerPixel; // left most column is `x` }
Well, that’s equal to magic, just a little optimized and neat: O
Although a goto usually allowed to leave two loops inside the inner loop, it is still ugly. Makes me really miss these great D flow control operations ...
The function you presented in the sample code does something else. It starts from a certain position in the image ( xx and yy is determined) and passes through count pixels going from the starting position to the right, continuing the next lines. It adds these alpha values to some array that I suspect.
When xx = yy = 0 passed, it will find the topmost pixel with certain conditions, not the leftmost one. This conversion is defined by the code above. Recall that a 2D image is just a 1D array in memory, starting from the top line from left to right and continuing with the following lines. Performing simple math, you can iterate over rows or columns.
source share