文章目錄
前言
Qt的QPainter十分強大,設置不同的組合模式,可以得到迥然不同的結果,比如調節圖片的透明度等,因此是否有必要弄清除QPainter的組合模式代表的意義。
研究相關
- Source指的是繪製的輸入,Destination指的是目的繪製區域本來存在的像素。
- 本文使用"Compositon Modes"程序對QPainter的組合模式進行解讀,其中花是繪製區域原來存在的像素,橢圓是繪製的輸入,Circle color是橢圓的的RGB通道數值,circle alpha是橢圓的透明通道數值。
QPainter::CompositionMode
QPainter::CompositionMode_SourceOver
- Qt幫組文檔描述:This is the default mode. The alpha of the source is used to blend the pixel on top of the destination.
- SourceOver是默認的繪製模式,繪製結果 = 繪製輸入*ratio_source + 目的區域原來像素 * ratio_destination。ratio_source和ratio_destination取決於繪製輸入的alpha通道值與繪製區域的alpha通道數值的比值(大部分取決於繪製區域的alpha數值,關係不是線性)。
- 測試數據
目的區域像素 | 輸入像素 | 結果 |
---|---|---|
(255, 255, 255, 10) | (0, 0, 0, 100) | (14, 14, 14, 102) |
(255, 255, 255, 10) | (0, 0, 0, 200) | (3,3,3,202) |
(255, 255, 255, 10) | (0, 0, 0, 255) | (0, 0, 0, 255) |
(255, 255, 255, 255) | (100, 0, 0, 200) | (133, 55, 55, 255) |
(255, 255, 255, 0) | (0, 0, 0, 200) | (0, 0, 0, 200) |
QPainter::CompositionMode_Source
- Qt幫組文檔描述:The output is the source pixel. (This means a basic copy operation and is identical to SourceOver when the source pixel is opaque).
- Source模式:繪製結果 = 繪製輸入,目的繪製區域原來的像素被完全覆蓋。
- 當繪製輸入的Alpha通道爲255(不透明時),Source和SourceOver模式的表現相同,因爲SourceOver模式中ratio_source = 1,ratio_destination = 0;
QPainter::CompositionMode_DestinationIn
- Qt幫組文檔描述:The output is the destination, where the alpha is reduced by that of the source. This mode is the inverse of CompositionMode_SourceIn.
- DestinationIn模式,最後的繪製結果爲原繪製區域圖像,但是其alpha通道數值會受到輸入的影響。
- 繪製結果 = 區域原像素(除Alpha通道外) + 區域原像素(Alpha通道)* 繪製輸入(Alpha通道)/ 255,繪製輸入(除Alpha通道)的值被丟棄,因此該模式一般僅用於設置繪製區域的透明度。
- 繪製結果通過代碼測試出來
- x = 200; 輸出爲1325400063(4EFFFFFF),Alpha通道值爲78(0x4E),而100 * (200/255) = 78.4313;
- x = 100;輸出爲671088639(27FFFFFF),Alpha通道爲39(0x27),而100 * (100/255) = 39.6825
- 測試代碼
QImage temp(QSize(100, 100), QImage::Format_ARGB32); temp.fill(QColor(255, 255, 255, 100)); QPainter painter(&temp); painter.setCompositionMode(QPainter::CompositionMode_DestinationIn); painter.fillRect(temp.rect(), QColor(0, 0, 0, x)); painter.end(); qDebug() << temp.pixel(50, 50);
- 繪製結果通過代碼測試出來
調節圖片透明度
/* 最後生成的img_res是img圖片的透明覆制 */
QPixmap temp(this->img.size());
temp.fill(Qt::transparent);
QPainter p1(&temp);
// CompositionMode_Source將圖片繪製進去
p1.setCompositionMode(QPainter::CompositionMode_Source);
p1.drawPixmap(0, 0, this->img);
// CompositionMode_DestinationIn設置圖片的透明度
p1.setCompositionMode(QPainter::CompositionMode_DestinationIn);
// 根據QColor中第四個參數設置透明度,此處position的取值範圍是0~255
p1.fillRect(temp.rect(), QColor(0, 0, 0, this->transparency * 255/100));
p1.end();
this->img_res = temp.copy();
寫在最後
- 目前只列舉了常見的三種CompositionMode,這三種模式可以用於調節圖片的透明度。後續將繼續補充。