I am taking an image of black pixels and drawing white rectangles with this function. The function takes positive and negative values for its dimensions, negative goes up and left while positive goes down and right. It takes positive values fine and I tried my best to account for negative values in my code, but when the height of the rectangle is negative, it is drawn all wrong. We can also assume the input is never going to go out of the bounds of the image. Why do negative widths come out incorrectly? I have other programs to draw this on screen. Example input: draw_rectangle( img, 20, 20, 10, 10 , 8, -8, 255 ); img is an array of pixels (uint8_t)
void draw_rectangle( uint8_t array[], unsigned int cols, unsigned int rows, int x,
int y, int rect_width, int rect_height, uint8_t color ){
unsigned int start = x + (y * cols);
unsigned int startDown;
unsigned int startOther;
if(rect_height > 0){
startDown = (x + ((y-1) * cols)) + (cols * rect_height);
} else if(rect_height < 0){
startDown = (x + ((y-1) * cols)) - (cols * rect_height * -1);
}
if(rect_width > 0){
startOther = ((x + (y * cols)) + rect_width -1);
} else if(rect_width < 0){
startOther = ((x + (y * cols)) - rect_width -1) ;
}
if(rect_width > 0 ){ //if the width is posivite
unsigned int drawIndex = 0;
while(drawIndex < rect_width){
//if((x + rect_width) < cols){
array[start + drawIndex] = color;
array[startDown + drawIndex] = color;
//}
drawIndex++;
}
} else if(rect_width < 0){ //if the width is negative
unsigned int posValue = rect_width * -1;
while(posValue > 0){
//if((x - rect_width) >= 0){
array[start - posValue + 1] = color;
array[startDown - posValue + 1] = color;
//}
posValue--;
}
}
if(rect_height > 0){
unsigned int drawIndex = 0;
while(drawIndex < rect_height){
//if((x + rect_width) < cols){
array[start + (drawIndex * cols)] = color;
array[startOther + (drawIndex * cols)] = color;
//}
drawIndex++;
}
} else if(rect_height < 0){ //if the height is negative
unsigned int posValue = rect_height * -1;
while(posValue > 0){
//if((x - rect_width) >= 0){
array[start - (posValue * cols)] = color;
array[start - (posValue * cols)] = color;
//}
posValue--;
}
}
}