gpt4 book ai didi

c++ - glOrtho 不改变 2D 窗口中的坐标系?

转载 作者:行者123 更新时间:2023-11-30 04:51:20 25 4
gpt4 key购买 nike

所以除非我理解错了,否则在默认的 OpenGL 窗口中坐标 (0,0) 位于屏幕的中心。我已经使用 glOrtho/glViewport 设置了以下调整大小功能,将左上角设置为 (0,0)。但出于某种原因,在 (0,0) 处绘制点仍然显示在屏幕中央(并且仍在 -1/1 范围内)。

主要

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setTitle("OpenGL");
w.resize(500,500);
w.show();
return a.exec();
}

主窗口.cpp

MainWindow::MainWindow(QWidget *parent)
{
setSurfaceType(QWindow::OpenGLSurface);
QSurfaceFormat format;
format.setProfile(QSurfaceFormat::CompatibilityProfile);
format.setVersion(2,1);

setFormat(format);
context =new QOpenGLContext;
context->setFormat(format);
context->makeCurrent(this);

openGLFuncions = context->functions();

}
void MainWindow::resizeGL(int w, int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,w,h,0.0,-1.0,1.0);
glMatrixMode(GL_MODELVIEW);
}

void MainWindow::paintGL()
{
glClearColor(0.0f,0.0f,0.0f,0.0f);
glClear(GL_COLOR_BUFFER_BIT);

glPointSize(10.0f);
glBegin(GL_POINTS);
glVertex2f(0.5f,0);
glEnd();

glFlush();
}

主窗体.h

class MainWindow : public QOpenGLWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
void updateAnim();
protected:
virtual void initilizeGL();
virtual void resizeGL(int w, int h);
virtual void paintGL();
void resizeEvent(QResizeEvent *event);
void paintEvent(QPaintEvent *event);
private:
QOpenGLContext *context;
QOpenGLFunctions *openGLFuncions;
};

最佳答案

我建议不要调用任何 OpenGL,MainWindow::initilizeGLMainWindow::paintGL 除外。

MainWindow类添加状态成员(_vp_valid),指示视口(viewport)和投影矩阵是否正确设置并初始化为false:

class MainWindow : public QOpenGLWindow
{

// [...]

private:

bool _vp_valid = false;

// [...]
};

如果状态无效,则更新视口(viewport)矩形并在MainWindow::paintGL中设置投影矩阵:

void MainWindow::paintGL()
{
if ( !_vp_valid )
{
_vp_valid = true;
int w = this->width();
int h = this->height();

glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,w,h,0.0,-1.0,1.0);
glMatrixMode(GL_MODELVIEW);
}

glClearColor(0.0f,0.0f,0.0f,0.0f);
glClear(GL_COLOR_BUFFER_BIT);

glPointSize(10.0f);
glBegin(GL_POINTS);
glVertex2f(0.5f,0);
glEnd();

glFlush();
}

MainWindow::resizeGL 中,足以使状态无效:

void MainWindow::resizeGL(int w, int h)
{
_vp_valid = false;
}

关于c++ - glOrtho 不改变 2D 窗口中的坐标系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54832391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com