c++ - 使用新参数第二次调用矩形绘图功能时出现问题
问题描述
我正在尝试创建一个程序,该程序会创建一个作为 PGM 图像文件读出的数字数组。我可以让程序写出到一个文本文件,其中一个矩形函数的实例工作,但不是第二个实例。我不明白为什么函数的第二个实例也没有改变数组。打印功能或矩形功能有问题吗?在观看了三个小时的视频后,我对正确方向的任何一点表示赞赏。
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
const int IMAGE_HEIGHT = 200;
const int IMAGE_WIDTH = 300;
const int GREY_SCALE = 255;
const int RECT1_TOP = 10;
const int RECT1_LEFT = 10;
const int RECT1_HEIGHT = 25;
const int RECT1_WIDTH = 50;
const int RECT1_GREY = 255;
const int RECT2_TOP = 50;
const int RECT2_LEFT = 30;
const int RECT2_HEIGHT = 25;
const int RECT2_WIDTH = 50;
const int RECT2_GREY = 200;
void createImage(unsigned char image[][IMAGE_WIDTH], int height);
bool writeImage(const unsigned char image[][IMAGE_WIDTH], int height);
void drawRect(unsigned char image[][IMAGE_WIDTH],
int imgHeight,
int rectTop,
int rectLeft,
int rectHeight,
int rectWidth,
unsigned char grayLevel);
int main()
{
unsigned char image[IMAGE_HEIGHT][IMAGE_WIDTH] = { };
createImage(image, IMAGE_HEIGHT);
writeImage(image, IMAGE_HEIGHT);
return 0;
}
void createImage(unsigned char image[][IMAGE_WIDTH], int height)
{
drawRect(image,
height,
RECT1_TOP,
RECT1_LEFT,
RECT1_HEIGHT,
RECT1_WIDTH,
RECT1_GREY);
drawRect(image,
height,
RECT2_TOP,
RECT2_LEFT,
RECT2_HEIGHT,
RECT2_WIDTH,
RECT2_GREY);
}
void drawRect(unsigned char image[][IMAGE_WIDTH],
int imgHeight,
int rectTop,
int rectLeft,
int rectHeight,
int rectWidth,
unsigned char grayLevel)
{
for (int rectRow = rectTop; rectRow < rectHeight; rectRow++)
{
for (int rectCol = rectLeft; rectCol < rectWidth; rectCol++)
image[rectRow][rectCol] = { grayLevel };
}
}
bool writeImage(const unsigned char image[][IMAGE_WIDTH], int height)
{
ofstream makeShapes;
makeShapes.open("makeShapes.txt");
makeShapes << "P2 \n";
makeShapes << IMAGE_WIDTH << " " << height << "\n";
for (int imageRow = 0; imageRow < height; imageRow++)
{
for (int imageColumn = 0; imageColumn < IMAGE_WIDTH; imageColumn++)
makeShapes << static_cast<int>(image[imageRow][imageColumn]) << ' ';
makeShapes << endl;
}
makeShapes.close();
return 1;
}
解决方案
首先,您在写出文件时遗漏了一条数据。在宽度和高度之后,您需要添加通道可以采用的最大值。所以你的文件输出应该是这样的:
P2
300 200
255
<...image data...>
接下来,您将矩形的宽度和高度传递给drawRect
,但它会将它们视为矩形的右侧和底部。当您为高度和宽度传入 25 和 50 时,左侧和顶部已经大于该值,因此外部循环甚至不会执行一次。您需要drawRect
像这样进行循环:
for (int rectRow = rectTop; rectRow < rectTop + rectHeight; rectRow++)
{
for (int rectCol = rectLeft; rectCol < rectLeft + rectWidth; rectCol++)
image[rectRow][rectCol] = { grayLevel };
}
推荐阅读
- sas - 如何在 SAS 中不均等地分箱数据?
- node.js - 如何使用 graphql 对日志进行精确查询?
- asp.net-core-mvc - 路由:使用双星号 (**) 包罗万象的参数语法时,仍会对正斜杠进行编码
- ios - 如何取消所有 Alamofire 请求?
- r - 是否可以在 R 中同时运行两个 while 循环?
- ios - 如何使用 Swift 从 QLPreviewController 中删除顶部不需要的空间
- r - 比较两行的快速方法
- php - 如何在 Opencart 上仅对一个自定义字段进行验证 - 已解决
- jenkins - 错误:无法在 jenkins 输出控制台中更新 svn repo
- django-models - ValueError:无法分配“''”:“”必须是“”实例。错误