常用绘图设备:
- QWidget
- QPixmap
- QBitmap
- QImage
- QPicture
代码:
//widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
//利用Image访问像素点
void paintEvent(QPaintEvent *);
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
//widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "QPainter"
#include "QPicture"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//QPixmap做绘图设备,对不同平台做了显示优化
QPixmap pix(300,300);
pix.fill(Qt::white);
QPainter painter(&pix);
painter.setPen(QPen(Qt::green));
painter.drawEllipse(QPoint(150,150),100,100);
pix.save("D:\\QT\\QtProjects\\14_QPaintDevice\\pix.png");
//QImage做绘图设备,专门为像素级访问做优化
QImage img(300,300,QImage::Format_RGB32);
img.fill(Qt::white);
QPainter painter(&img);
painter.setPen(QPen(Qt::green));
painter.drawEllipse(QPoint(150,150),100,100);
img.save("D:\\QT\\QtProjects\\14_QPaintDevice\\img.png");
//QPicture做绘图设备 记录和重现画家的绘图指令
QPicture pic;
QPainter painter;
painter.begin(&pic);
painter.setPen(QPen(Qt::red));
painter.drawEllipse(QPoint(150,150),100,100);
painter.end();
pic.save("D:\\QT\\QtProjects\\14_QPaintDevice\\pic.zt");//后缀名自定义,不影响
}
void Widget::paintEvent(QPaintEvent *){
QPainter painter(this);
QImage img;
img.load(":/imgs/Luffy.png");
for(int i=50;i<100;i++){
for(int j=50;j<100;j++){
QRgb val = img.pixel(j,i);
img.setPixel(i,j,val);
}
}
painter.drawImage(0,0,img);
//重现QPicture的绘图
QPainter painter(this);
QPicture pic;
pic.load("D:\\QT\\QtProjects\\14_QPaintDevice\\pic.zt");
painter.drawPicture(0,0,pic);
}
Widget::~Widget()
{
delete ui;
}