我需要使用线方程算法创建线,其中x1,y1和x2,y2的值是通过鼠标输入。这是我漫长的编码 -
#include <stdio.h>;
#include <GL/glut.h>;
int counter;
int x1, x2;
int y1, y2;
void setPixel(int x, int y)
{
float m;
float b;
float x3, y3;
x3 = x2-x1;
y3 = y2-y1;
if(counter==1)
{
glPointSize(9.0f);
glBegin(GL_POINTS);
m = y3 / x3;
while(x1 <= x2)
{
b = y - (m*x2);
y = (m*x1)+b;
y = 400-y;
glVertex2i(x1,y);
x1++;
}
glEnd();
glFlush();
}
}
void myMouse(int button, int state, int x, int y)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN )
{
setPixel(x,y);
counter++;
if(counter==0)
{
x1 = x;
y1 = y;
}
if(counter==1)
{
x2 = x;
y2 = y;
}
}
}
void myKeyboardAct(unsigned char c, int x, int y)
{
switch(c)
{
case 's' : //show coordinates' x and y
printf("what where and what are x and y %d %d \n" ,x,y);
printf("what where and what are x and y %d %d \n" ,x2,y2);
break;
case 'e' : //flush and draw
glFlush();
break;
}
}
void myDisplay(void)
{
glClearColor(0,0,0,0);
glColor3f(200.0,0.00,0);
gluOrtho2D(-300.0,300.0,-200.0,200.0);
//gluOrtho2D(0.0,600.0,400.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glutMouseFunc(myMouse);
glFlush();
}
int main(int argc, char** argv)
{
glutInitWindowSize(600,400);
//glutInitWindowSize(1024,800);
glutInitWindowPosition(100,100);
glutCreateWindow("HELLO THERE YOU CAN JUST DRAW AWAYYYY DRAW AWAAAAAYYYYYYYYYYYYYYYYYYYY");
glutDisplayFunc(myDisplay);
glutKeyboardFunc(myKeyboardAct);
glutMainLoop ();
return 0;
}
然而,我遇到的问题是该线似乎出现在我点击的上方几点或几点以下。另一件事是,如果渐变为负,则不会出现该行。
答案 0 :(得分:0)
首先测试是否从鼠标获得正确的坐标。
在将鼠标位置复制到点之前调用setPixel()!试试这样:
void myMouse(int button, int state, int x, int y)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN )
{
if(counter==0) { x1=x; y1=y; counter++; }
if(counter==1) { x2=x; y2=y; }
setPixel(x,y);
}
}
你的Draw系列有很多错误,这是一个分配因此我不会修复它只是给你提示