利用C语言画图例子
1)
/*#include <graphics.h>// 就是需要引用这个图形库 #include
<conio.h> void main()
#include<stdio.h>
#include <conio.h>
void main()
{
initgraph(640, 480); // 这里和 TC 略有区别
circle(200, 200, 100); // 画圆,圆心(200, 200),半径 100 getch(); // 按任意键继续
closegraph(); // 关闭图形界面
printf("***\n");
}
*/
2)
/*
#include <graphics.h>
#include <time.h>
#include <conio.h>
void main()
{
// 设置随机函数种子
srand((unsigned) time(NULL));
// 初始化图形模式
initgraph(640, 480);
int x, y;
char c;
setfont(16, 8, "Courier"); // 设置字体
while(!kbhit())
{
for (int i=0; i<479; i++)
{
setcolor(GREEN);
for (int j=0; j<3; j++)
{
x = (rand() % 80) * 8;
y = (rand() % 20) * 24;
c = (rand() % 26) + 65;
outtextxy(x, y, c);
}
setcolor(0);
line(0,i,639,i);
Sleep(10);
if (kbhit()) break;
}
}
// 关闭图形模式
closegraph();
}
*/
3)
/*
#include <graphics.h>
#include <time.h>
#include <conio.h>
#define MAXSTAR 200 // 星星总数
struct STAR
{
double x;
int y;
double step;
int color;
};
STAR star[MAXSTAR];
// 初始化星星
void InitStar(int i)
{
star[i].x = 0;
star[i].y = rand() % 480;
star[i].step = (rand() % 5000) / 1000.0 + 1;
star[i].color = (int)(star[i].step * 255 / 6.0 + 0.5);
// 速度越快,颜色越亮
star[i].color = RGB(star[i].color, star[i].color,
star[i].color);
}
// 移动星星
void MoveStar(int i)
{
// 擦掉原来的星星
putpixel((int)star[i].x, star[i].y, 0);
// 计算新位置
star[i].x += star[i].step;
if (star[i].x > 640) InitStar(i);
// 画新星星
putpixel((int)star[i].x, star[i].y, star[i].color); }
// 主函数
void main()
{
srand((unsigned)time(NULL)); // 随机种子
initgraph(640, 480); // 打开图形窗口
// 初始化所有星星
for(int i=0; i<MAXSTAR; i++)
{
InitStar(i);
star[i].x = rand() % 640;
}
// 绘制星空,按任意键退出
while(!kbhit())
{
for(int i=0; i<MAXSTAR; i++)
MoveStar(i);
Sleep(20);
}
closegraph(); // 关闭图形窗口
}
*/
4)
/*
#include <graphics.h>
#include <conio.h>
void main()
{
float H, S, L;
initgraph(640, 480);
// 画渐变的天空(通过亮度逐渐增加)
H = 190; // 色相
S = 1; // 饱和度
L = 0.7f; // 亮度
for(int y = 0; y < 480; y++)
{
L += 0.0005f;
setcolor( HSLtoRGB(H, S, L) );
line(0, y, 639, y);
}
// 画彩虹(通过色相逐渐增加)
H = 0;
S = 1;
L = 0.5f;
setlinestyle(PS_SOLID, NULL, 2); // 设置线宽为 2 for(int r = 400; r > 344; r--)
{
H += 5;
setcolor( HSLtoRGB(H, S, L) );
circle(500, 480, r);
}
getch();
closegraph();
}
*/
5)
#include <graphics.h>
#include <conio.h>
void main()
{
// 初始化图形窗口
initgraph(640, 480);
MOUSEMSG m; // 定义鼠标消息
while(true)
{
// 获取一条鼠标消息
m = GetMouseMsg();
switch(m.uMsg)
{
case WM_MOUSEMOVE:
// 鼠标移动的时候画红色的小点
putpixel(m.x, m.y, RED);
break;
case WM_LBUTTONDOWN:
// 如果点左键的同时按下了 Ctrl 键
if (m.mkCtrl)
// 画一个大方块
rectangle(m.x-10, m.y-10, m.x+10, m.y+10);
else
// 画一个小方块
rectangle(m.x-5, m.y-5, m.x+5, m.y+5);
break;
case WM_RBUTTONUP:
return; // 按鼠标右键退出程序}
}
// 关闭图形窗口
closegraph();
}。