如何使 QImage 或 QPixmap 半透明 - 或者为什么 setAlphaChannel 已过时? [英] How to make a QImage or QPixmap semi-transparent - or why is setAlphaChannel obsolete?

查看:59
本文介绍了如何使 QImage 或 QPixmap 半透明 - 或者为什么 setAlphaChannel 已过时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

4.7 and like to overlay two images on a qgraphicsview. The image on top shall be semi-transparent to allow to see through it. Initially both images are fully opaque. I expected some function for setting a global alpha-value for each pixel to exist, but it seems like there is no such function. The closest thing to it is QPixmap::setAlphaChannel(const QPixmap & alphaChannel), which, however, is marked as obsolete since Qt-4.6. Instead the manual refers to the CompositionModes of QPainter, but I don't succeed to add transparency to an opaque image like I want. Could anyone point me to a working example or share some code?

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

I'm almost sorry for having an own answer, now just a few hours after asking the question. From this article I figured out that the following code does the job. I just wonder if this is considered "better" (which often translates to faster) than modifying the alpha values pixelwise.

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

推荐答案

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

The Qt's composition demo can be a bit intimidating, because they try to show everything off. Hopefully the demo plus the QPainter documentation is helpful for you. You want to use CompositionMode::SourceOver and make sure that the images are converted to ARGB32 (premultiplied). From the documentation:

当绘制设备为 QImage 时,图像格式必须设置为 Format_ARGB32Premultiplied 或 Format_ARGB32 才能使合成模式产生任何效果.为提高性能,预乘版本是首选格式.

这篇关于如何使 QImage 或 QPixmap 半透明 - 或者为什么 setAlphaChannel 已过时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆