#include "mainwindow.h"
#include <QPainter>
#include <QTimer>
#include <QKeyEvent>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      m_fTimer(new QTimer(this)),
      m_status(false),
      m_time(0)
{
    setWindowTitle("幸运大转盘");
    setFixedSize(500,500);
    m_fTimer->stop();
    m_fTimer->setInterval(10);
    connect(m_fTimer,SIGNAL(timeout()),this,SLOT(on_timer_timeout()));
}

MainWindow::~MainWindow()
{

}

void MainWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    drawBackground(&painter);
    drawPointe(&painter);
}

void MainWindow::drawBackground(QPainter *painter)
{
    QImage img("://bk.png");
    painter->drawImage(0,0,img);
}

void MainWindow::drawPointe(QPainter *painter)
{
     QPixmap img("://3.png");
     int rangle = 20*m_time;
     if(rangle % 30 ==0){
         rangle +=1;
     }
     img = rotateImageWithTransform(img,rangle);
     painter->drawPixmap(0,0,500,500,img);
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Return){
        if(m_status){
            m_status = false;
            m_fTimer->stop();
        }
        else{
            m_status = true;
            m_fTimer->start();
        }
    }
}


QPixmap MainWindow::rotateImageWithTransform(const QPixmap &src, int angle)
{
    QMatrix matri;
    //迁移到中心
    matri.translate(src.width()/2.0,src.height()/2.0);
    //中心旋转
    matri.rotate(angle);
    //回退中心
    matri.translate(-src.width()/2.0,-src.height()/2.0);
    //执行坐标映射变化
    //旋转后图像大小变化了 需要提前进行裁剪 如果在旋转后裁剪
    //则需要计算使用三角函数计算
    //中心偏移
    int cubeWidth = qMin(src.width(),src.height());
    QRect cubeRect(0,0,cubeWidth,cubeWidth);
    cubeRect.moveCenter(src.rect().center());
    auto retImg = src.copy(cubeRect);
    retImg = retImg.transformed(matri,Qt::SmoothTransformation);
    return retImg;
}

void MainWindow::on_timer_timeout()
{
    m_time ++;
    if(m_time == 360/20){
        m_time = 0;
    }
    update();
}
