绘图(打开jpg,bmp文件显示)
1,QBitmap和QPixmap的使用
widgt.cpp
#include "widget.h"
#include "ui_widget.h"
#include
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *)
{
QPainter p(this);
//QPixmap 图片背景透明
p.drawPixmap(0, 0, QPixmap("../Image/butterfly.png"));
//QBitmap 图片背景透明
p.drawPixmap(200, 0, QBitmap("../Image/butterfly.png"));
//QPixmap 图片背景白色
QPixmap pixmap;
pixmap.load("../Image/butterfly1.png");
p.drawPixmap(0, 200, pixmap);
//QBitmap 图片背景白色
QBitmap bitmap;
bitmap.load("../Image/butterfly1.png");
p.drawPixmap(200, 200, bitmap);
}
widgt.h
#ifndef WIDGET_H
#define WIDGET_H
#include
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
protected:
//重写绘图事件
//如果给窗口绘图,一定要在paintEvent()绘图
void paintEvent(QPaintEvent *);
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
2,背景填充:
#include "widget.h"
#include "ui_widget.h"
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//绘图设备, 400*300
QPixmap pixmap(400, 300);
QPainter p(&pixmap);
//填充白色背景色
//p.fillRect(0, 0, 400, 300, QBrush(Qt::white));
pixmap.fill(Qt::white);
p.drawPixmap(0, 0, 80, 80, QPixmap("../Image/face.png"));
//保存图片
pixmap.save("../pixmap.jpg");
}
Widget::~Widget()
{
delete ui;
}
3,setpixel 函数功能:该函数将指定坐标处的像素设为指定的颜色。
#include "widget.h"
#include "ui_widget.h"
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//创建一个绘图设备,QImage::Format_ARGB32背景是透明
QImage image(400, 300, QImage::Format_ARGB32);
QPainter p;
p.begin(&image);
//绘图
p.drawImage(0, 0, QImage("../Image/face.png"));
//对绘图设备前50个像素点进行操作
for(int i = 0; i < 50; i++)
{
for(int j = 0; j < 50; j++)
{
image.setPixel(QPoint(i, j), qRgb(0, 255, 0));
//image.pixel(QPoint(i, j));
}
}
p.end();
image.save("../image.png");
}
Widget::~Widget()
{
delete ui;
}
4,QPicture的使用:
#include "widget.h"
#include "ui_widget.h"
#include
#include
#include
#include
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QPicture picture;
QPainter p;
p.begin(&picture);
p.drawPixmap(0, 0, 80, 80, QPixmap("../Image/face.png"));
p.drawLine(50, 50, 150, 50);
p.end();
//保存的是二进制文件
picture.save("../picture.png");
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *)
{
#if 0
QPicture pic;
pic.load("../picture.png"); //加载文件
QPainter p(this);
p.drawPicture(0, 0, pic);
#endif
QPainter p(this);
QPixmap pixmap;
pixmap.load("../Image/face.png");
//QPixmap -> QImage
QImage tempImage = pixmap.toImage();
p.drawImage(0, 0, tempImage);
QImage image;
image.load("../Image/face.png");
//QImage -> QPixmap
QPixmap tempPixmap = QPixmap::fromImage(image);
p.drawPixmap(100, 0, tempPixmap);
}