Search code examples
javaopenglgraphicsgeometrylwjgl

LWJGL/OpenGL drawn lines not completely meeting in corners


I've created a method that draws a black border around a drawn texture. The border lines however do create little gaps at the corners. I think it has to do with the width of the border and tried to add the borderwidth to the length of the lines, but this makes them to short with some borderwidth values and to big with other borderwidth values.

The black lines are the borders

public static void DrawBorder(float x, float y, float width, float height) {
    float borderWidth = 10.0f;
    glColor3f(0, 0, 0);
    glLineWidth(borderWidth);
    glTranslatef(x, y, 0);

    glBegin(GL_LINE_LOOP);
    glVertex2f(0, 0);
    glVertex2f(width, 0);
    glVertex2f(width, height);
    glVertex2f(0, height);
    glEnd();
    glColor3f(255, 255, 255);
}

Solution

  • OpenGL does not draw end caps on lines, and it does not join lines together. There are two ways to solve this:

    1. Make each line a little longer, by borderWidth/2. This means that your lines can't share vertices.

    2. (Recommended) Use triangles instead. Something like this:

      float border = 10.0f;
      glColor3f(0, 0, 0);
      glTranslatef(x, y, 0);
      glBegin(GL_TRIANGLE_STRIP);
      glVertex2f(    0,      0); glVertex2f(      - border,        - border);
      glVertex2f(width,      0); glVertex2f(width + border,        - border);
      glVertex2f(width, height); glVertex2f(width + border, height + border);
      glVertex2f(    0, height); glVertex2f(      - border, height + border);
      glVertex2f(    0,      0); glVertex2f(      - border,        - border);
      glEnd();