简体   繁体   中英

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:

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.
2)Find the difference in the X and Y co-ordinates values as dx and dy.
3)Check if dx is greater of dy is greater and assign the greater value to 'steps'.
4)Increment X and Y values at regular intervals by dividing the corresponding axes difference by steps.
5)Plot the initial point by using “PUTPIXEL” syntax.
6)Repeat step 4 'steps' number of times and mark the end point by using “PUTPIXEL” syntax.
7)End the program.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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