Tinting a QPixmap using QPainter (CompositionMode_Overlay)



  • I'm having some issues tinting a QPixmap.

    My code is:

          image.load(imagePath); // load the image
          QPainter *paint = new QPainter(&image);
          paint->setCompositionMode(QPainter::CompositionMode_Overlay); // I want the box to blend into the image
          QRectF rectangle(0.0, 0.0, 45, 45); // the rectangle
          color.setAlpha(brightness); // I am setting the alpha so that the colour is actually visible
          paint->fillRect(rectangle, color); // this is the issue - it changes the alpha on the image, I want the alpha 255 pixels to be coloured in, not alpha 0.
          delete paint;
          color = colors;
          brightness = brightnessSlider;
          return image;
    

    This is my source image: http://i.imgur.com/ZkcYJfg.png
    This is the result: http://i.imgur.com/gPKbY9l.png (please ignore the size difference)

    The problem is that the source image has a transparent background (alpha 0), and my sprite, has pixels which are opaque (alpha 255). However, the overlay mode ignores this, and decides to tint all of my source image.
    The mode 'CompositionMode_Atop' sort of works, however it does not have the same desired effect as the Overlay mode.

    Ideally, I would like the result to have a transparent background, and also to be tinted using the Overlay mode.

    Thanks, VOT.


  • Qt Champions 2016

    @Votato said:
    Hi
    Maybe you have tried it, but i wonder if you could use the
    http://doc.qt.io/qt-4.8/qimage.html#createAlphaMask
    with painter setClipRegion
    so you only affect the area you want.
    Like here:
    http://stackoverflow.com/questions/7539257/how-to-use-a-mask-with-qpainter


  • Moderators

    You can do this in two steps:

    QPainter p;
    
    QImage img(imagePath);
    QImage mask(img);
    
    p.begin(&mask);
    p.setCompositionMode(QPainter::CompositionMode_SourceIn);
    p.fillRect(rect, color);
    p.end();
    
    p.begin(&img);
    p.setCompositionMode(QPainter::CompositionMode_Overlay);
    p.drawImage(0, 0, mask);
    p.end();
    
    return img;
    

    Btw. Don't create painters on the heap. Dynamic allocation is slower than stack values. It also requires lifetime management (delete) which makes your code unnecessary complex.



Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.