2010-11-13 292 views
4

4.7并且喜欢在qgraphicsview上叠加两个图像。顶部的图像应该是半透明的,以便透过它。最初,两幅图像都完全不透明。我期望一些函数为每个像素设置一个全局的alpha值,但似乎没有这样的函数。最接近它的是QPixmap :: setAlphaChannel(const QPixmap & alphaChannel),但是,自Qt-4.6以后,它被标记为废弃。相反,手册引用了QPainter的CompositionModes,但我没有成功将透明度添加到像我想要的不透明图像。 任何人都可以指向我的工作示例或共享一些代码?如何使QImage或QPixmap半透明 - 或为什么setAlphaChannel已过时?

编辑: 我几乎很抱歉有一个自己的答案,现在就提问后几个小时。 从这article我发现下面的代码完成这项工作。我只是想知道这是否被认为是“更好”(通常意味着更快),而不是按照像素方式修改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)); 

回答

6

Qt's composition demo可能有点吓人,因为他们试图展示一切。希望演示加上QPainter documentation对你有帮助。您想使用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.

+0

谢谢你做了我的问题我用QPainter :: CompositionMode_Source :) – jamk 2013-01-24 13:44:44

2

首先,对于内部操作上的图像,通常你需要使用的QImage代替的QPixmap,为QPixmap的直接访问功能受到限制。原因是QPixmaps存储在呈现设备上,例如, X服务器上的像素图或GL纹理。另一方面,从QPixmap到QImage并返回是昂贵的,因为它通常会导致从图形卡内存复制到主内存并返回。

正如我所看到的,您需要一种操作,只更改像素的Alpha值,使其原始值完整无缺。一个解决方案,是不是优雅,但工作原理,如下:

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; 
    } 
} 

注:这是快得多改变的QImage的每个像素,然后做painter.drawImage()比绘制与手相应的字母每一个像素。

6

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

void ClassName::paintEvent(QPaintEvent *event) 
{ 
    QPainter painter(this); 
    painter.setOpacity(1.00); //0.00 = 0%, 1.00 = 100% opacity. 
    painter.drawPixmap(QPixmap(path)); 
}