2010-11-13 289 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)); 
}