简体   繁体   English

使用 Bresenham Line Algorithm 打印点而不是线的垂直线

[英]Vertical line using Bresenham Line Algorithm printing a point, not a line

I am trying to do vertical lines using Bresenham's Line Algorithm.我正在尝试使用 Bresenham 的线算法做垂直线。 But when I put coordinate for a vertical line, it is printing a point only, not showing a vertical line.但是当我为垂直线放置坐标时,它只打印一个点,而不是显示垂直线。

#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

     int main( )
     {
         int x1,y1,x2,y2,dx,dy,ds,dt,d,x,y;
         /* request auto detection */
         int gdriver = DETECT, gmode, errorcode;
      
        /* initialize graphics and local variables */
         initgraph(&gdriver, &gmode, "c:\\tc\\bgi");

         x1=200;
         x2=200;
         y1=200;
         y2=300;

         x=x1;
         y=y1;
         dx=x2-x1;
         dy=y2-y1;
         dt=2*(dy-dx);
         ds=2*dy;
         d=2*dy-dx;

         printf("Using Bresenham's Line Algorithm");
         putpixel(x,y,7);

         while(x<=x2)
            {
            x=x+1;
            if(d<0)
                 d=d+ds;
            else
                 {
                y=y+1;
                d=d+dt;
                 }
            putpixel(x,y,7);
            }

           getch();
       closegraph();
       return 0;
}

When I put x1=200 x2=200 it gives me an error.当我输入 x1=200 x2=200 时,它给了我一个错误。 Why am I getting the error?为什么我会收到错误消息? But in normal line function, I am getting the right result, but when putting in Bresenham, I am getting the wrong result.但是在正常的线函数中,我得到了正确的结果,但是当放入 Bresenham 时,我得到了错误的结果。

Bresenham like you implemented can only draw lines with a slope between 0° and 45° since every loop increases x by one and conditionally increases y by one.像您实现的 Bresenham 只能绘制斜率在 0° 和 45° 之间的线,因为每个循环都会将 x 增加 1 并有条件地将 y 增加 1。

What you have to do is first check if the line goes left to right.您要做的是首先检查线路是否从左到右。 If not you have to switch the endpoints.如果不是,您必须切换端点。

Next if the line slopes down instead of up you have to decrement y instead of incrementing it.接下来,如果线向下而不是向上倾斜,则必须减少 y 而不是增加它。 You can store 1 or -1 in a temp variable depending on whether the lines slopes up or down and add that to y when needed.您可以将1-1存储在临时变量中,具体取决于线条是向上还是向下倾斜,并在需要时将其添加到y中。

And if the change in y is greater than the change in x you have to swap the coordinates around in the algorithm incrementing y every loop and x conditionally.如果 y 的变化大于 x 的变化,你必须在算法中交换坐标,每个循环增加 y 和有条件地增加 x。 For this you actually have to duplicate the whole loop.为此,您实际上必须复制整个循环。

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

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