在计算机图形学中,绘制各种曲线和图形是一个常见的任务,而C语言是一个广泛应用于图形编程的语言之一。今天,我们将使用C语言和EasyX图形库来绘制一个五次曲线波形。
首先,我们需要安装EasyX图形库。EasyX是一个简单易用的图形库,适用于C语言的图形界面开发。你可以在EasyX的官方网站下载并安装它,然后就可以开始我们的项目了。
我们将使用C语言编写我们的绘图程序。以下是我们的代码
///////////////////////////////////////////////////
// 程序名称:五次波形曲线绘制
// 编译环境:Mictosoft Visual Studio 2022, EasyX_20200315(beta)
// 作 者:luoyh <2864292458@qq.com>
// 最后修改:2024-5-9
//
#define _CRT_SECURE_NO_WARNINGS
#include <graphics.h>
#include <math.h>
#include <conio.h>
#include <stdio.h>
const int WIDTH = 480;
const int HEIGHT = 480;
const int X_ORIGIN = WIDTH / 2;
const int Y_ORIGIN = HEIGHT / 2;
void drawGrid()
{
// 绘制横线
setlinestyle(PS_DOT, 1); // 设置线型为虚线,宽度为1
setcolor(RED); // 设置颜色为红色
for (int i = 0; i < HEIGHT; i += 20)
{
line(0, i, WIDTH, i);
}
// 绘制竖线
for (int i = 0; i < WIDTH; i += 20)
{
line(i, 0, i, HEIGHT);
}
}
void drawAxes()
{
// 绘制坐标轴
setcolor(YELLOW); // 设置颜色为色
setlinestyle(PS_SOLID, 1); // 设置线型为实线,宽度为1
settextcolor(WHITE);
// x轴
line(0, Y_ORIGIN, WIDTH, Y_ORIGIN);
for (int i = -10; i <= 10; i++)
{
int x = X_ORIGIN + i * 20;
if (x != X_ORIGIN)
{
line(x, Y_ORIGIN - 3, x, Y_ORIGIN + 3);
char label[5];
sprintf(label, '%d', i);
outtextxy(x - 5, Y_ORIGIN + 5, label);
}
}
// y轴
line(X_ORIGIN, 0, X_ORIGIN, HEIGHT);
for (int i = -10; i <= 10; i++)
{
int y = Y_ORIGIN - i * 20;
if (y != Y_ORIGIN)
{
line(X_ORIGIN - 3, y, X_ORIGIN + 3, y);
char label[5];
sprintf(label, '%d', i);
outtextxy(X_ORIGIN - 20, y - 5, label);
}
}
// 绘制箭头
line(WIDTH - 10, Y_ORIGIN, WIDTH - 20, Y_ORIGIN - 10); // x轴箭头
line(WIDTH - 10, Y_ORIGIN, WIDTH - 20, Y_ORIGIN + 10);
line(X_ORIGIN, 10, X_ORIGIN - 10, 20); // y轴箭头
line(X_ORIGIN, 10, X_ORIGIN + 10, 20);
// 绘制刻度值
outtextxy(WIDTH - 20, Y_ORIGIN + 15, 'X'); // x轴标签
outtextxy(X_ORIGIN + 15, 10, 'Y'); // y轴标签
outtextxy(X_ORIGIN + 5, Y_ORIGIN + 5, 'O'); // 原点标签
}
int main()
{
initgraph(WIDTH, HEIGHT); // 初始化图形界面
// 绘制背景网格
drawGrid();
// 绘制坐标轴
drawAxes();
// 绘制五次曲线波形
float x, y;
for (int i = -X_ORIGIN; i < X_ORIGIN; i++)
{
x = i + X_ORIGIN;
y = Y_ORIGIN - pow(x - X_ORIGIN, 5) / 3000000; // 五次方程 y = (x - X_ORIGIN)^5 / 3000000
putpixel(x, y, WHITE);
}
// 等待用户关闭窗口
_getch();
closegraph();
return 0;
}
联系客服