中点画线
#include <GL/glut.h>
#include<math.h>
#include<iostream>
using namespace std;
void Midpoint(float x0, float y0, float x1, float y1)
{
int flag = 0;
float a, b, d, x, y;
//k>1
if (abs(x1 - x0) < abs(y1 - y0)) {
swap(x0, y0);
swap(x1, y1);
flag = 1;
}
if (x0 > x1) {
swap(x0, x1);
swap(y0, y1);
}
//窗口清为黑色
glClear(GL_COLOR_BUFFER_BIT);
a = y0 - y1;
b = x1 - x0;
d = 2 * a + b;
if (y0 < y1) {//斜率为正
x = x0;
y = y0;
//画点
glBegin(GL_POINTS);
GLfloat n = x1 - x;
GLfloat cnt = 0;
GLfloat colorChange = cnt / n;
glColor3f(1.0, 0, 0);
glVertex2f(x0 / 1000, y0 / 1000);
glEnd();
while (x < x1) {
x++;
cnt++;
colorChange = cnt / n;
if (d < 0) {
y++;
d += 2 * (a + b);
}
else {
d += 2 * a;
}
if (flag == 1) {
glBegin(GL_POINTS);
glColor3f(1.0* colorChange, 0, 0);
glVertex2f(y / 1000, x / 1000);
glEnd();
}
else {
glBegin(GL_POINTS);
glColor3f(1.0 * colorChange, 0, 0);
glVertex2f(x / 1000, y / 1000);
glEnd();
}
}
glFlush();
}
else {
x = x1;
y = y1;
GLfloat n = x-x0;
GLfloat cnt = 0;
GLfloat colorChange = cnt / n;
//画点
glBegin(GL_POINTS);
glColor3f(1.0 * colorChange, 0, 0);
glVertex2f(x0 / 1000, y0 / 1000);
glEnd();
while (x > x0) {
x--;
cnt++;
colorChange = cnt / n;
if (d < 0) {
y++;
d = d - 2 * a + 2 * b;
}
else {
d = d - 2 * a;
}
if (flag == 1) {
glBegin(GL_POINTS);
glColor3f(1.0 * colorChange, 0, 0);
glVertex2f(y / 1000, x / 1000);
glEnd();
}
else {
glBegin(GL_POINTS);
glColor3f(1.0 * colorChange, 0, 0);
glVertex2f(x / 1000, y / 1000);
glEnd();
}
}
glFlush();
}
}
void display(void) {
float x0, y0, x1, y1;
cout << "请输入起始点和终点坐标" << endl;
cin >> x0 >> y0 >> x1 >> y1;
Midpoint(x0, y0, x1, y1);
}
void main(int argc, char** argv) {
glutInit(&argc, argv); //初始化glut
glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE | GLUT_RGBA);
//设置窗口的模式-深度缓存,单缓存,颜色模型
glutInitWindowPosition(200, 200); //设置窗口的位置
glutInitWindowSize(400, 400); //设置窗口的大小
glutCreateWindow("Line"); //创建窗口并赋予title
glutDisplayFunc(display);//调用display把绘制传送到窗口,这个函数的原型为glutDisplayFunc(void)
glutMainLoop(); //进入循环等待
}
结果
DDA算法
void DDA(float x0, float y0, float x1, float y1) {
float dm = 0;
if (abs(x1-x0) < abs(y1 - y0)) {
dm = abs(y1 - y0);
}
else dm = abs(x1 - x0);
float dx = (float)(x1 - x0) / dm;
float dy = (float ) (y1 - y0) / dm;
float x = x0, y = y0;
glPointSize(6.0f);
GLfloat precise = 0.25;
glBegin(GL_POINTS);
for (float i = 0; i < dm; i+=precise) {
glColor3f(i/dm, 0, 0);
x += dx * precise;
y += dy * precise;
glVertex2f(x , y );
}
glEnd();
}
添加一些细节结果如下
Quote
图形学---中点画线法---opengl中实现