How to do it…

Let's create a simple demo that shows the effect of different image compositions by following these steps:

  1. First, set up a new Qt Widgets Application project and remove the menuBar, mainToolBar, and statusBar, as we did in the first recipe.
  2. Next, add the QPainter class header to the mainwindow.h file:
#include <QPainter>
  1. After that, declare the paintEvent() virtual function, like so:
virtual void paintEvent(QPaintEvent* event);
  1. In mainwindow.cpp, we will first load several image files using the QImage class:
void MainWindow::paintEvent(QPaintEvent* event) {
QImage image;
image.load("checker.png");

QImage image2;
image2.load("tux.png");

QImage image3;
image3.load("butterfly.png");
}
  1. Then, create a QPainter object and use it to draw two pairs of images, where one image is on top of another:
QPainter painter(this);
painter.drawImage(QPoint(10, 10), image);
painter.drawImage(QPoint(10, 10), image2);
painter.drawImage(QPoint(300, 10), image);
painter.drawImage(QPoint(300, 40), image3);
  1. Compile and run the program now and you should see something like this:

  1. Next, we will set the composition mode before drawing each image onscreen:
QPainter painter(this);
painter.setCompositionMode(QPainter::CompositionMode_Difference);
painter.drawImage(QPoint(10, 10), image);
painter.setCompositionMode(QPainter::CompositionMode_Multiply);
painter.drawImage(QPoint(10, 10), image2);
painter.setCompositionMode(QPainter::CompositionMode_Xor);
painter.drawImage(QPoint(300, 10), image);
painter.setCompositionMode(QPainter::CompositionMode_SoftLight);
painter.drawImage(QPoint(300, 40), image3);
  1. Compile and run the program again and you will now see something like this:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset