简体   繁体   中英

How To Draw a line with variables

for example,In the following code, in the function “glVertex3f”, a constant between 1 and-1 is used to represent a point

glBegin(GL_LINES);
{
glColor3ub(255, 0, 0);
glVertex3f(-1,0,0);glVertex3f(1,0,0);
}

But most of the time, we use 'variables' more often. Suppose the width of the window is 450, and half of it is 225. The parameter input range is between 0 and 225, and when we enter an integer according to this interval, I expect to get a proportional decimal value and use this decimal value to draw a straight line.

void DrawLine(GLint ix, GLint iy,GLint ia,GLint ib)
{
    GLfloat width = 225;
    GLfloat x, y, z;
    GLfloat a, b, c;
    x = (GLfloat)(ix / width);
    y = (GLfloat)(iy / width);
    z = 0.2;
    a = (GLfloat)(ia / width);
    b = (GLfloat)(ib / width);
    c = 0.2;

    glBegin(GL_LINES);
    {
        glColor3ub(255, 0, 0);
        glVertex3f(x, y, z); glVertex3f(a, b, c);
    }
    glEnd();
}

The above program doesn't work at all. Please tell me what the problem is.

ix / width is an integral division You have to cast ix to a float, to do a floation point division:

x = (GLfloat)(ix) / (GLfloat)(width);

Normalized device coordinates are in range [-1.0, 1.0]. There for the conversion from NDC to window coordinates is:

x = (GLfloat)(ix) / (GLfloat)(width) * 2.0f - 1.0f; 

However, I recommend to use an Orthographic projection which maps window coordinates to NDC:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, width, -1, 1);

With this projection matrix you can use the integral window coordinates ( ix , iy , ...) directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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