[英]How to center an opengl window with glfw?
我想在屏幕中央画一个 opengl window,但是我到处搜索但没有找到任何答案。 下面是创建 window 的常见代码段,但它总是出现在大多数左上角 position 中。我该如何控制它。
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();
}
}
请使用此 function“ glfwSetWindowPos ”。
这是一个例子。
@Himanshu answered a question on how to get the max-width and max-height of a window aka window size How to get maximum possible window size when creating window in MFC? 因此,使用那段代码,您可以将其居中,如下所示:
int width=800;// could declare them as "const int" if you like
int hight=800;
GLFWwindow* window = glfwCreateWindow(width,hight, "OpenGL", NULL, NULL);
int max_width = GetSystemMetrics(SM_CXSCREEN);
int max_hieght = GetSystemMetrics(SM_CYSCREEN);
glfwSetWindowMonitor(window, NULL, (max_width/2)-(width/2), (max_hieght/2) - (height/2), width, height, GLFW_DONT_CARE);
这是我的游戏引擎的一个示例,它使用glad 和glfw 制作,它使用windows api 来查找屏幕分辨率,然后相应地将window 居中。
#include <iostream>
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <GLFW/glfw3.h>
#include <Windows.h>
const unsigned int width = 1600;
const unsigned int height = 900;
const char* title = "Frog2D";
void getDesktopResolution(int& horizontal, int& vertical)
{
RECT desktop;
const HWND hDesktop = GetDesktopWindow();
GetWindowRect(hDesktop, &desktop);
horizontal = desktop.right;
vertical = desktop.bottom;
}
int main()
{
glfwInit();
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); //borderless
int horizontal = 0;
int vertical = 0;
getDesktopResolution(horizontal, vertical);
GLFWwindow* window = glfwCreateWindow(width, height, title, NULL, NULL);
glfwSetWindowPos(window, horizontal / 2 - width / 2, vertical / 2 - height / 2);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.