컴퓨터 공학/Qt

[ Qt 프로그래밍 ] OpenGL 로 2D 사각형 만들기

혼새미로 2015. 11. 26. 23:47
반응형

OpenGL로 2D 시점의 사각형을 만들어보겠습니다.

 

아래 코드는 첨부파일에 올려둔 프로젝트에서 OpenGL부분의 클래스입니다.

 

 

Colored By Color Scripter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#ifndef GLWIDGET_H
#define GLWIDGET_H
 
#include <QGLWidget>
 
class QTimer;
 
class GLWidget : public QGLWidget
{
    Q_OBJECT
public:
    GLWidget();
    ~GLWidget();
 
private:
    void paintGL(); //GL그리는 함수
    void initializeGL(); //GL초기화하는 함수
    void resizeGL(int w, int h);  //위젯 크기변했을때 호출하는 함수
 
    QTimer* timer; //타이머 변수
 
    GLfloat x1; //사각형 위치
    GLfloat y1;
    GLfloat rsize; //사각형 크기
 
    GLfloat xstep; //이동
    GLfloat ystep;
 
    GLfloat windowWidth; //위젯길이
    GLfloat windowHeight; //위젯높이
 
 
 
 
private slots:
    void timerFunction();
};
 
#endif // GLWIDGET_H
 

 

 

Colored By Color Scripter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "glwidget.h"
#include <QTimer>
 
GLWidget::GLWidget()
{
    x1=0.0f;
    y1=0.0f;
    rsize=15;
 
    xstep=5.0f;
    ystep=5.0f;
 
    timer=new QTimer(this);
    timer->setInterval(17);
    connect(timer,SIGNAL(timeout()),this,SLOT(timerFunction()));
    timer->start();
}
 
GLWidget::~GLWidget()
{
    delete timer;
}
 
void GLWidget::initializeGL()
{
    glClearColor(0.0f,0.0f,0.0f,1.0f);
    glColor3f(0.0f,1.0f,0.0f);
    //glEnable(GL_FOG);
 
}
 
void GLWidget::resizeGL(int w, int h)
{
    GLfloat aspectRatio;
 
    if(h==0)
        h=1;
 
    glViewport(0,0,w,h);
 
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
 
    aspectRatio=(GLfloat)w/(GLfloat)h;
    if(w<=h)
    {
        windowWidth=100;
        windowHeight=100/aspectRatio;
        glOrtho(-100.0,100.0,-windowHeight,windowHeight,1.0,-1.0);
    }
    else
    {
        windowWidth=100*aspectRatio;
        windowHeight=100;
        glOrtho(-windowWidth,windowWidth,-100.0,100.0,1.0,-1.0);
    }
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}
 
void GLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0f,0.0f,0.0f);
    glRectf(x1,y1,x1+rsize,y1-rsize);
}
 
void GLWidget::timerFunction()
{
    if(x1>windowWidth-rsize||x1<-windowWidth)
        xstep=-xstep;
    if(y1>windowHeight||y1<-windowHeight+rsize)
        ystep=-ystep;
 
    x1+=xstep;
    y1+=ystep;
 
    if(x1>(windowWidth-rsize+xstep))
        x1=windowWidth-rsize-1;
    else if(x1<-(windowWidth+xstep))
        x1=-windowWidth-1;
 
    if(y1>(windowHeight+ystep))
        y1=windowHeight-1;
    else if(y1<-(windowHeight-rsize+ystep))
        y1=-windowHeight+rsize-1;
 
    repaint();
 
}
 

 

 

 

 

첨부파일에 올려둔 프로젝트를 실행하면 다음과 같이 보입니다.

 


 

 

프로젝트파일은 자유롭게 사용해도 됩니다.

 

반응형