mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimerEvent>
#include <QPaintEvent>
class MainWindow : public QMainWindow
{
Q_OBJECT
QPolygon *polygon;
QPointF pts[4];
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
void paintEvent(QPaintEvent* e);
void timerEvent(QTimerEvent *e);
void rotateRect(float a);
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include <QPainter>
#include <QPolygon>
#include <cmath>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
//원점을 중심으로 위치한 정사각형의 꼭지점 좌표
pts[0] = QPointF(-50,-50);
pts[1] = QPointF(50,-50);
pts[2] = QPointF(50,50);
pts[3] = QPointF(-50,50);
polygon = new QPolygon(4); // 4개의 꼭지점을 갖는 다각형
for(int i=0;i<4;i++){
polygon->setPoint(i,pts[i].x(),pts[i].y());
}
startTimer(50);
}
MainWindow::~MainWindow(){}
void MainWindow::paintEvent(QPaintEvent *e)
{
QPainter painter(this);
rotateRect(0.1F);
painter.setBrush(QBrush("#ff0000"));
painter.drawPolygon(*polygon);
}
void MainWindow::timerEvent(QTimerEvent *e)
{
repaint();
}
void MainWindow::rotateRect(float a)
{
/* 행렬을 이용한 점(벡터)의 회전(원점을 중심으로 Θ라디안 회전)
cos(Θ), -sin(Θ) px
sin(Θ), cos(Θ) * py
-------------------------
x' = cos(Θ)*px - sin(Θ)*py
y' = sin(Θ)*px + cos(Θ)*py
*/
for(int i=0;i<4;i++){
float x = cos(a)*pts[i].x() - sin(a)*pts[i].y();
float y = sin(a)*pts[i].x() + cos(a)*pts[i].y();
pts[i].setX(x);
pts[i].setY(y);
polygon->setPoint(i,
pts[i].x()+width()/2,
pts[i].y()+height()/2
);
}
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.resize(550, 450);
w.setWindowTitle(QString::fromLocal8Bit("행렬을 이용한 회전"));
w.show();
return a.exec();
}