简体   繁体   English

澄清C图形库的框架代码

[英]Clarification on skeleton code for C graphics library

I'm studying C and I've been given this code which draws a single line of pixels: 我正在研究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);
    }       

I understand how it works, but not how to implement it. 我了解它是如何工作的,但不知道如何实现它。 Could someone provide an example of how to use it? 有人可以提供一个使用示例吗?

Hope This will help you: 希望这个能对您有所帮助:

Algorithm: 算法:
1)Get the X and Y co-ordinates of the start and end points of the line. 1)获取直线起点和终点的X和Y坐标。
2)Find the difference in the X and Y co-ordinates values as dx and dy. 2)在X和Y坐标值中找到差异dx和dy。
3)Check if dx is greater of dy is greater and assign the greater value to 'steps'. 3)检查dx是否大于dy,然后将更大的值分配给“ steps”。
4)Increment X and Y values at regular intervals by dividing the corresponding axes difference by steps. 4)通过将相应的轴差逐步除以规则的间隔增加X和Y值。
5)Plot the initial point by using “PUTPIXEL” syntax. 5)使用“ PUTPIXEL”语法绘制初始点。
6)Repeat step 4 'steps' number of times and mark the end point by using “PUTPIXEL” syntax. 6)重复步骤4的“步骤”次数,并使用“ PUTPIXEL”语法标记终点。
7)End the program. 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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM