7

4.7 并且喜欢在 qgraphicsview 上叠加两个图像。顶部的图像应该是半透明的,以便可以看穿它。最初,两个图像都是完全不透明的。我希望有一些函数可以为每个像素设置一个全局 alpha 值,但似乎没有这样的函数。最接近它的是 QPixmap::setAlphaChannel(const QPixmap & alphaChannel),然而,它自 Qt-4.6 起就被标记为过时了。相反,该手册引用了 QPainter 的 CompositionModes,但我没有成功地将透明度添加到我想要的不透明图像中。谁能指出我的工作示例或分享一些代码?

编辑: 我几乎很抱歉有一个自己的答案,现在就在问这个问题几个小时后。从这篇文章中,我发现以下代码可以完成这项工作。我只是想知道这是否被认为比逐像素修改 alpha 值“更好”(通常转化为更快)。

QPainter p; 
p.begin(image);
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
p.fillRect(image->rect(), QColor(0, 0, 0, 120));
p.end();            
mpGraphicsView->scene()->addPixmap(QPixmap::fromImage(image->mirrored(false,true),0));  
4

3 回答 3

9

使用您的画家对象并设置不透明度。

void ClassName::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setOpacity(1.00);  //0.00 = 0%, 1.00 = 100% opacity.
    painter.drawPixmap(QPixmap(path));
}
于 2014-04-01T15:52:02.373 回答
8

Qt 的组合演示可能有点吓人,因为它们试图炫耀一切。希望演示和QPainter 文档对您有所帮助。您想使用 CompositionMode::SourceOver 并确保将图像转换为 ARGB32(预乘)。从文档中:

When the paint device is a QImage, the image format must be set to Format_ARGB32Premultiplied or Format_ARGB32 for the composition modes to have any effect. For performance the premultiplied version is the preferred format.

于 2010-11-13T13:31:54.860 回答
2

First of all, for internal operations on images, often you need to use QImage instead of QPixmap, as the direct access functionality to QPixmap is restricted. Reason is that QPixmaps are stored on the rendering device, e.g. pixmap on the X server or GL texture. On the other hand, going from QPixmap to QImage and back is expensive as it often results in copying from the graphics card memory to main memory and back.

As I see it you need an operation that changes only the alpha value of the pixels, leaving their original values intact, for blitting. One solution that is not elegant, but works, is the following:

for (int y = 0; y < image.height() ++y) {
  QRgb *row = (QRgb*)image.scanLine(y);
  for (int x = 0; x < image.width(); ++x) {
    ((unsigned char*)&row[x])[3] = alpha;
  }
}

Note: it is much faster to alter each pixel of the QImage, and then do painter.drawImage() than drawing each pixel with corresponding alpha by hand.

于 2010-11-13T14:18:56.633 回答