使用 QPixmap 的 transformed 函数来实现旋转,这个函数默认是以图片中心为旋转点,不能设置旋转的中心点,使用如下:
- QMatrix matrix;
- matrix.rotate(45);
-
- QLabel *Label= new QLabel();
- Label->setPixmap(QPixmap(“:/images.png”)
- .transformed(matrix, Qt::SmoothTransformation));
使用 QPainter 这位“画家”,示例程序如下:
- void Widget::paintEvent(QPaintEvent *)
- {
- QPainter painter(this);
- QPixmap disc(":/disc.png");
-
- /* 设定旋转中心点 */
- painter.translate(130,150);
- /* 旋转的角度 */
- painter.rotate(45);
- /* 恢复中心点 */
- painter.translate(-130,-150);
- /* 画图操作 */
- painter.drawPixmap(40,60,180,180, disc);
- }
-
- QMatrix matrix;
- matrix.rotate(angle);
- if(angle++ ==360)
- angle = 0;
- //设定图片的大小;
- QImage Image = QImage(":/images/cd.png");
- QPixmap pixmap = QPixmap::fromImage(Image);
- QPixmap fixpixmap = pixmap.scaled(320,320,Qt::IgnoreAspectRatio
- ,Qt::SmoothTransformation);
-
- QLabel *Label= new QLabel();
- label[1]->setPixmap((fixpixmap)
- .transformed(matrix,Qt::SmoothTransformation));
- label[1]->setAlignment(Qt::AlignCenter);
使用 QPainter 这位“画家”,示例程序如下:
- MainWindow::MainWindow(QWidget *parent)
- : QMainWindow(parent)
- {
- disc = QPixmap(":/cd.png");
- timer = new QTimer();
- timer->start(10);
- connect(timer,SIGNAL(timeout()),this,SLOT(timerTimeOut()));
- }
-
- void MainWindow::paintEvent(QPaintEvent *)
- {
- QPainter painter(this);
- /* 碟机转动 */
- if(angle++ == 360)
- angle = 0;
- /* 设定旋转中心点 */
- painter.translate(disc.width()/2,disc.height()/2);
- /* 旋转的角度 */
- painter.rotate(angle);
- /* 恢复中心点 */
- painter.translate(-disc.width()/2,-disc.height()/2);
- /* 画图操作 */
- painter.drawPixmap(0,0,disc.width(),disc.height(), disc);
- }
-
- void MainWindow::timerTimeOut()
- {
- /* 当界面初始化或者需要刷新时才会执行paintEvent */
- update();
- }
- void MainWindow::paintEvent(QPaintEvent *)
- {
- QPainter painter(this);
- painter.setRenderHints(QPainter::Antialiasing
- | QPainter::SmoothPixmapTransform);
- /* 碟机转动 */
- if(angle++ == 360)
- angle = 0;
- //设定旋转中心点
- /* QRectF 即,继承 QRect(Qt 的矩形类), F 代表精确到浮点类型 */
- QRect rect((this-> width() - disc.width()) / 2,
- (this-> height() - disc.height()) / 2,
- disc.width(),
- disc.height());
- /* 默认参考点为左上角原点(0,0),因为旋转需要以图形的中心为参考点,
- * 我们使用 translate 把参考点设置为 CD 图形的中心点坐标 */
- painter.translate(0 + rect.x() + rect.width() / 2,
- 0 + rect.y() + rect.height() / 2);
- /* 旋转的角度 */
- painter.rotate(angle);
- //恢复中心点;
- /* 现在参考点为 CD 图形的中心,我们需要把它设置回原点的位置,
- * 所以需要减去上面加上的数 即将绘图的起点设置回起点*/
- painter.translate(0 - (rect.x() + rect.width() / 2),
- 0 - (rect.y() + rect.height() / 2));
- //画图操作
- /* 画图,QPainter 提供了许多 drawX 的方法 */
- painter.drawPixmap(rect,disc);
- }
最终效果: