我正在拍摄黑色像素的图像并使用此函数绘制白色矩形。该函数的维度取正值和负值,负值向上和向左移动,正值向下和向右移动。它需要正值,我尽力在代码中考虑负值,但是当矩形的高度为负值时,它会被完全绘制错误。我们还可以假设输入永远不会超出图像的范围。为什么负宽度显示不正确?我有其他程序可以在屏幕上绘制它。 输入示例: 绘制矩形( 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--;
}
}
}
最佳答案
我认为您可能忘记更改此处的“else if”代码块:
里面不应该有“startOther”吗,就像宽度 block 一样?
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--;
}
}
即 尝试改变这个:
array[start - (posValue * cols)] = color;
array[start - (posValue * cols)] = color;
对此:
array[start - (posValue * cols)] = color;
array[startOther - (posValue * cols)] = color;
关于c - 在灰度像素图像中绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26395117/