1. 程式人生 > >OPENGL—中點Bresenham畫直線

OPENGL—中點Bresenham畫直線

//中點Bresenham畫直線
#include "stdafx.h"
#include <gl/glut.h>
#include <cmath>

void init(void)    
{
     glClearColor(1.0,1.0,1.0,1.0);    //設定背景顏色為白色    
     glMatrixMode(GL_PROJECTION);       //對投影相關進行操作 
     gluOrtho2D(0.0, 30.0, 0.0, 30.0);
 }

 void putpixel(int x, int y)
{
    glColor3f(1.0, 0.0, 0.0);      
    glPointSize(2.0f);
    glBegin(GL_POINTS);
        glVertex2f(15+x, 15+y);
    glEnd();
    glFlush();
}

void MidBresenhamLine(int x0,int y0,int x1,int y1)
{
	int dx,dy,d,UpIncre,DownIncre,x,y;
	if(x0>x1){
		x=x1;
		x1=x0;
		x0=x;
		y=y1;
		y1=y0;
		y0=y;
	}
	x=x0;
	y=y0;
	dx=x1-x0;
	dy=y1-y0;
	d=dx-2*dy;
	UpIncre=2*dx-2*dy;
	DownIncre=-2*dy;
	while(x<=x1)
	{
		putpixel(x,y);
		x++;
		if(d<0)
		{
			y++;
			d+=UpIncre;
		}
		else
			d+=DownIncre;
	}
}

void display()
 {
     glClear(GL_COLOR_BUFFER_BIT);       
     MidBresenhamLine(0,0,8,6);    
 }
 
 int main(int argc,char** argv)
 {

     glutInit(&argc,argv);
     glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);  
     glutInitWindowSize(400,400);   
     glutInitWindowPosition(0,0);    
     glutCreateWindow("中點Bresenham畫直線");   
     glutDisplayFunc(display);    
     init();       
     glutMainLoop();   
 
     return 0;
 }
執行結果: