cpp使用graphics绘制指定数量的矩形
时间: 2023-08-01 18:15:12 浏览: 42
可以使用graphics.h库中的rectangle函数来绘制矩形。下面是一个绘制指定数量矩形的示例代码:
```cpp
#include <graphics.h>
int main() {
// 初始化图形模式
initgraph(640, 480);
// 绘制10个矩形
for (int i = 0; i < 10; i++) {
int x = i * 50 + 50;
int y = 100;
int w = 40;
int h = 30;
rectangle(x, y, x + w, y + h);
}
// 等待用户关闭窗口
getch();
// 关闭图形模式
closegraph();
return 0;
}
```
该代码会在窗口中绘制10个矩形,每个矩形之间相距50个像素。你可以根据需要调整矩形的位置和大小。注意,在使用graphics.h库时,需要在编译选项中加入 `-l graphics` 参数。
相关问题
cpp使用graphics绘制指定数量的随机位置的矩形
下面是一个使用 `graphics.h` 库实现指定数量的随机位置矩形绘制的示例代码:
```cpp
#include <graphics.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
// 设置随机数种子
srand(time(NULL));
// 矩形数量
int count = 50;
for (int i = 0; i < count; i++) {
// 随机位置和大小
int x = rand() % getmaxx();
int y = rand() % getmaxy();
int w = rand() % 50 + 10;
int h = rand() % 50 + 10;
// 随机颜色
setcolor(rand() % 15 + 1);
// 绘制矩形
rectangle(x, y, x + w, y + h);
}
getch();
closegraph();
return 0;
}
```
在上面的代码中,我们使用 `srand(time(NULL))` 设置随机数种子,确保每次运行程序时生成的随机数不同。然后使用 `rand()` 函数生成随机位置和大小,并使用 `setcolor()` 函数设置随机颜色。最后使用 `rectangle()` 函数绘制矩形。
注意:使用 `graphics.h` 库需要在编译选项中添加 `-lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32`。
c++使用graphics绘制指定数量随机位置的矩形
下面是一个使用C++的graphics库绘制指定数量随机位置的矩形的示例代码:
```cpp
#include <graphics.h>
#include <cstdlib>
#include <ctime>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
int num_rectangles = 10; // 绘制矩形的数量
int max_width = getmaxx() / 4; // 矩形的最大宽度
int max_height = getmaxy() / 4; // 矩形的最大高度
srand(time(NULL)); // 初始化随机数生成器
for (int i = 0; i < num_rectangles; i++) {
int x = rand() % (getmaxx() - max_width); // 随机生成矩形的x坐标
int y = rand() % (getmaxy() - max_height); // 随机生成矩形的y坐标
int w = rand() % max_width + 1; // 随机生成矩形的宽度
int h = rand() % max_height + 1; // 随机生成矩形的高度
setcolor(rand() % 16 + 1); // 随机生成矩形的颜色
rectangle(x, y, x+w, y+h); // 绘制矩形
}
getch();
closegraph();
return 0;
}
```
这个程序使用了`graphics.h`库来进行图形绘制。我们首先使用`initgraph()`函数初始化绘图环境。然后,我们定义了绘制矩形的数量,以及矩形的最大宽度和高度。接下来,我们使用`srand()`函数初始化随机数生成器,然后在循环中随机生成矩形的位置、宽度、高度和颜色,并使用`rectangle()`函数绘制矩形。最后,我们使用`getch()`函数等待用户按下任意键,然后使用`closegraph()`函数关闭绘图环境,释放资源。
这个程序可以绘制指定数量的随机位置、大小和颜色的矩形。你可以根据自己的需要调整绘制的矩形数量和大小,并修改颜色的范围。