Search code examples
c++openglwindowglfw

How to center an opengl window with glfw?


I wanna draw an opengl window in center of the screen,however I searched everywhere but didn't find any answer to it. Below is a common snippet code of creating a window But it always show up in most left-top position.How can I control it.

int main()
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
    glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(400,200,"LearnOpenGl",NULL,NULL);
    if(window == NULL)
    {
        cout<<"Failed to create GLFW window!!"<<endl;
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        cout<<"Failed to initialize GLAD!!"<<endl;
        return -1;
    }

    glViewport(400, 400, 100, 200);

    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    while(!glfwWindowShouldClose(window))
    {
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

}

Solution

  • Please use this function "glfwSetWindowPos".

    Here is an example.