澄清C图形库的骨架代码

时间:2015-04-26 03:01:19

标签: c graphics teensy

我正在学习C并且我已经获得了这个代码,它绘制了一行像素:

void draw_line(unsigned char x1, unsigned char y1, unsigned char x2, unsigned char y2) {
// Insert algorithm here.
if (x1 == x2) {
    //Draw Horizontal line
    unsigned char i;
    for (i = y1; i <= y2; i++){
        set_pixel(x1, i, 1);
    }           
} else if (y1 == y2){
    //Draw vertical line
    unsigned char i;
    for (i = x1; i <= x2; i++){
        set_pixel(i, y1, 1);
    }       

我理解它是如何工作的,但不知道如何实现它。有人可以举例说明如何使用它吗?

1 个答案:

答案 0 :(得分:0)

希望这会对你有所帮助:

算法:
1)获取线的起点和终点的X和Y坐标 2)找出X和Y坐标值的差异为dx和dy 3)检查dx是否大于dy,并将更大的值分配给'steps' 4)通过将相应的轴差除以步长,以规则的间隔增加X和Y值 5)使用“PUTPIXEL”语法绘制初始点 6)重复步骤4'步骤'次数并使用“PUTPIXEL”语法标记终点 7)结束程序。

Program:
#include"graphics.h"
#include"stdio.h"
#include"conio.h"
#include"math.h"
void linedraw(int,int,int,int);
int main()
{
int x1coeff,y1coeff,x2coeff,y2coeff;
printf("\Enter the x and y value for starting point:");
scanf("%d%d",&x1coeff,&y1coeff);
printf("\Enter the x and y value for end point:");
scanf("%d%d",&x2coeff,&y2coeff);
linedraw(x1coeff,y1coeff,x2coeff,y2coeff);
getch();
return 0;
}
void linedraw(int xa,int ya,int xb,int yb)
{
int dx,dy,steps,k;
int gdriver=DETECT,gmode;
float xinc,yinc,x,y;
initgraph(&gdriver,&gmode,""); //initialise graphics
dx=xb-xa;
dy=yb-ya;
x=xa;
y=ya;
if(abs(dx)>abs(dy))
{
steps=abs(dx);
}
else
{
steps=abs(dy);
}
xinc=dx/steps;
yinc=dy/steps;
putpixel(x,y,WHITE);
for(k=0;k {
x+=xinc;
y+=yinc;
putpixel(x,y,WHITE);
}}
Output:
Enter the x and y value for starting point:100 100
Enter the x and y value for end point:200 200
The Line drawn is

enter image description here