我正在使用此功能拍摄黑色像素的图像并绘制白色矩形。该函数的尺寸取正值和负值,负值向上和向左,正值向下和向右。它采用正值很好,我尽我所能在我的代码中考虑负值,但是当矩形的高度为负时,它被画错了。我们还可以假设输入永远不会超出图像的范围。为什么负宽度输出不正确?我有其他程序可以在屏幕上绘制它。示例输入:draw_rectangle(img, 20, 20, 10, 10, 8, -8, 255); img 是一个像素数组(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--;
}
}
}