1. 程式人生 > 其它 >Qt QPixmap設定圖片透明度

Qt QPixmap設定圖片透明度

最近看到美圖秀秀的一些功能,可以手動設定圖片的透明度並顯示在其它圖片上,所以自己動手做了個小Demo,實際效果如下:

(圖片僅供參考使用)

可以看到拖動下方進度條,可以控制左上角圖片的透明度。

方法如下:

新建一個Qt專案,在UI介面上拖放一個QLabel和一個QSlider,設定QSlider的數值範圍為0~255,簡單佈局下即可。

程式碼如下:

 1 #ifndef WIDGET_H
 2 #define WIDGET_H
 3  
 4 #include <QWidget>
 5 #include <QPixmap>
 6 #include <QPainter>
 7
#include <QLabel> 8 9 namespace Ui { 10 class Widget; 11 } 12 13 class Widget : public QWidget 14 { 15 Q_OBJECT 16 17 public: 18 explicit Widget(QWidget *parent = 0); 19 ~Widget(); 20 21 private slots: 22 void on_horizontalSlider_sliderMoved(int position); 23 24 private
: 25 Ui::Widget *ui; 26 27 QLabel *m_label; //設定透明度的圖片的label 28 }; 29 30 #endif // WIDGET_H
 1 #include "widget.h"
 2 #include "ui_widget.h"
 3  
 4 #include <QDebug>
 5 Widget::Widget(QWidget *parent) :
 6     QWidget(parent),
 7     ui(new Ui::Widget)
 8 {
 9     ui->setupUi(this
); 10 11 //設定背景label的圖片 12 QPixmap pix_("./test.jpg"); 13 ui->label->setPixmap(pix_); 14 15 //設定新的lable位置 16 m_label = new QLabel(ui->label); 17 m_label->setScaledContents(true); 18 m_label->setGeometry(10,10,200,150); 19 m_label->raise(); 20 m_label->show(); 21 } 22 23 Widget::~Widget() 24 { 25 delete ui; 26 } 27 28 void Widget::on_horizontalSlider_sliderMoved(int position) 29 { 30 //設定新的圖片的透明度 31 QPixmap pix1_("./test.jpg"); 32 33 QPixmap temp(pix1_.size()); 34 temp.fill(Qt::transparent); 35 36 QPainter p1(&temp); 37 p1.setCompositionMode(QPainter::CompositionMode_Source); 38 p1.drawPixmap(0, 0, pix1_); 39 p1.setCompositionMode(QPainter::CompositionMode_DestinationIn); 40 41 //根據QColor中第四個引數設定透明度,此處position的取值範圍是0~255 42 p1.fillRect(temp.rect(), QColor(0, 0, 0, position)); 43 p1.end(); 44 45 pix1_ = temp; 46 m_label->setPixmap(pix1_); 47 }
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <ui version="4.0">
 3  <class>Widget</class>
 4  <widget class="QWidget" name="Widget">
 5   <property name="geometry">
 6    <rect>
 7     <x>0</x>
 8     <y>0</y>
 9     <width>400</width>
10     <height>300</height>
11    </rect>
12   </property>
13   <property name="windowTitle">
14    <string>Widget</string>
15   </property>
16   <layout class="QGridLayout" name="gridLayout">
17    <item row="0" column="0">
18     <layout class="QVBoxLayout" name="verticalLayout">
19      <item>
20       <widget class="QLabel" name="label">
21        <property name="text">
22         <string/>
23        </property>
24       </widget>
25      </item>
26      <item>
27       <widget class="QSlider" name="horizontalSlider">
28        <property name="maximum">
29         <number>255</number>
30        </property>
31        <property name="orientation">
32         <enum>Qt::Horizontal</enum>
33        </property>
34       </widget>
35      </item>
36     </layout>
37    </item>
38   </layout>
39  </widget>
40  <layoutdefault spacing="6" margin="11"/>
41  <resources/>
42  <connections/>
43 </ui>