首页 > 代码库 > 中点Brehensam画线算法

中点Brehensam画线算法

#include<stdio.h>

#include<stdlib.h>

#include"graphics.h"

 

//函数声明

void MidBrehansem(int x0, int y0, int x1, int y1);  //中点MidBrehansem算法

void swap(int &x, int &y);  //利用引用传递交换值

 

int main()

{

    int gdriver = DETECT, gmode;

    int x0, y0, x1, y1;

 

    printf("Please input start point:\n");

    scanf("%d%d", &x0, &y0);

    printf("Please input end point:\n");

    scanf("%d%d", &x1, &y1);

 

    initgraph(&gdriver, &gmode, "");

 

    MidBrehansem(x0, y0, x1, y1);

   

    system("pause");

 

    closegraph();

 

    return 0;

}

 

//中点MidBrehansem算法

void MidBrehansem(int x0, int y0, int x1, int y1)

{

    int  dx, dy,i,di;

    double k;

 

    if (x0 > x1)

    {

        swap(x0, x1);

        swap(y0, y1);

    }

 

    int x = x0, y = y0;     //定义到前面会从x1,y1开始画线

 

    dx = x1 - x0;

    dy = y1 - y0;

 

    k = 1.0*dy / dx;

    i = (abs(dy)>abs(dx)) ? abs(dy): abs(dx);

 

    if (k > 1)

    {

        di = 2 * dx + dy;

        while (i--)

        {

            putpixel(x, y, RED);

            if (di >= 0)

            {

                di += 2 * (dx - dy);

                x++;

            }

            else

                di += 2 * dx;

 

            y++;

        }

    }

    else if (k >= 0 && k < 1)

    {

        di = dx - 2 * dy;

        while (i--)

        {

            putpixel(x, y, YELLOW);

            if (di < 0)

            {

                di += 2 * (dx - dy);

                y++;

            }

            else

                di += (-2)*dy;

 

            x++;

        }

    }

    else if (k >= -1 && k < 0)

    {

        di = -dx - 2 * dy;

        while (i--)

        {

            putpixel(x, y, YELLOW);

            if (di >= 0)

            {

                di += (-2)*(dx + dy);

                y--;

            }

            else

                di += (-2)*dy;

 

            x++;

        }

    }

    else

    {

        di = -2 * (dx + dy);

        while (i--)

        {

            putpixel(x, y, WHITE);

            if (di < 0)

            {

                di += (-2)*(dx + dy);

                x++;

            }

            else

                di += (-2)*dx;

 

            y--;

        }

    }

   

}

 

//利用引用传递交换值

void swap(int &x, int &y)

{

    int t;

 

    t = x;

    x = y;

    y = t;

}

技术分享技术分享技术分享技术分享

中点Brehensam画线算法