Qt的QPainter::CompositionMode提供了多種圖像疊加的模式。常見的有QPainter::CompositionMode_SourceOver, QPainter::CompositionMode_SourceAtop,git
QPainter::CompositionMode_DestinationOver和QPainter::CompositionMode_DestinationAtop。如今逐個描述這四種模式的效果。函數
從http://www.tuicool.com/articles/NF3qIb下載了兩幅尺寸相等圖片:ui
如今用第一幅圖片作掩蓋,與第二幅圖片合成this
1)QPainter::CompositionMode_DestinationOverspa
- #include "mainwindow.h"
- #include <QMessageBox>
- #include <QFileDialog>
- #include <QPainter>
- #include <QPaintEvent>
- MainWindow::MainWindow(QWidget *parent)
- : QMainWindow(parent)
- {
- QString filename;
- filename=QFileDialog::getOpenFileName(this,
- tr("選擇圖像"),
- "",
- tr("Images (*.png *.bmp *.jpg *.tif *.GIF )"));
- if(filename.isEmpty())
- {
- return;
- }
- else
- {
- if(! ( m_img.load(filename) ) ) //加載圖像
- {
- QMessageBox::information(this,
- tr("打開圖像失敗"),
- tr("打開圖像失敗!"));
- return;
- }
- m_img.load(filename);
- }
- filename=QFileDialog::getOpenFileName(this,
- tr("選擇mask"),
- "",
- tr("Images (*.png *.bmp *.jpg *.tif *.GIF )"));
- if(filename.isEmpty())
- {
- return;
- }
- else
- {
- if(! ( m_mask.load(filename) ) ) //加載圖像
- {
- QMessageBox::information(this,
- tr("打開圖像失敗"),
- tr("打開圖像失敗!"));
- return;
- }
- m_mask.load(filename);
- }
- }
- MainWindow::~MainWindow()
- {
- }
- void MainWindow::paintEvent(QPaintEvent *e)
- {
- QImage * newImage = new QImage(m_img);
- QImage * mask = new QImage(m_mask);
- QPainter painter;
- painter.begin(mask);
- painter.setCompositionMode(QPainter::CompositionMode_DestinationOver);
- painter.drawImage(0, 0, * newImage);
- painter.end();
- painter.begin(this);
- painter.drawImage(e->rect(), * mask);
- painter.end();
- delete mask;
- delete newImage;
- }
注: m_mask和m_img都是QImage類型的變量,也是MainWindow類的成員。一個表明掩蓋圖,一個表明花瓶圖。運行程序時,MainWindow的構造函數會先詢問哪個文件是被遮擋的花瓶圖。你選定以後,MainWindow會再次詢問哪個是掩蓋圖。選定以後,程序自動調用paintEvent,把兩個圖合成。.net
效果:code
2)CompositionMode_DestinationAtoporm
將painter.setCompositionMode(QPainter::CompositionMode_DestinationOver)一句改成painter.setCompositionMode(QPainter::CompositionMode_DestinationAtop)便可。blog
效果和1)相同。圖片
3)CompositionMode_SourceAtop
將painter.setCompositionMode(QPainter::CompositionMode_DestinationOver)一句改成painter.setCompositionMode(QPainter::CompositionMode_SourceAtop)便可。
效果:
4)CompositionMode_SourceOver。遮蓋不起做用。