Search code examples
qticonsalphaqpainter

Qt drawing icons using color and alpha-map


I would like to draw icons (only one color) in different colors. To do so, I would like to import a single alpha-texture and then combine this with a given color in the application.

The result should be, that nothing is drawn on to the background, when the alpha-map has an opacity of 0 and the used color should be drawn, when the opacity is 1.

One soulution should be hidden somewhere in QPainter, since you can manually set the Composition-Mode (QPainter::setCompositionMode). But I don't get it to work like I want.

Does somebody have an idea?

Thanks in advance.

EDIT: Here is a little graphic explaining what I would like to do. I want to use a Alpha-Map like shown in the graphic and then use a color layer to create my icon. Important is, that the background stays transparent.

enter image description here


Solution

  • You can do thos using QPainter like this:

    QColor color;
    // set color value
    
    // load gray-scale image (an alpha map)
    QPixmap pixmap = QPixmap(":/images/earth.png");
    
    // initialize painter to draw on a pixmap and set composition mode
    QPainter painter(&pixmap);
    painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
    
    painter.setBrush(color);
    painter.setPen(color);
    
    painter.drawRect(pixmap.rect());
    
    // Here is our new colored icon!
    QIcon icon = QIcon(pixmap);
    

    Here is gray-scale image and two colored icons which i get using the code above (QPixmap.save() method): icons