前言
實現一個簡單的小工具,使用Qt QML實現Windows桌面顏色提取器,實時顯示鼠標移動位置的顏色值,包括十六進制值和RGB值。該功能在實際應用中比較常見,比如截圖的時候,鼠標移動就會在鼠標位置實時顯示坐標和顏色值,做項目實現UI的時候可能會經常用到這個功能,快速提取設計圖的顏色值。
效果圖如下:
代碼使用Qt 5.15.2版本實現,QML實現UI交互。
后期可以在此基礎上擴展更多的功能,比如鼠標右鍵的時候,就暫停提取,然后添加一個復制按鈕,可以方便復制當前的顏色值,然后直接取用。
正文
實現原理就是移動移動的時候,實時在屏幕鼠標處截取圖片然后獲取圖片上的顏色值。
QPixmap pixmap = screen->grabWindow(0, screenPos.x(), screenPos.y(), 1, 1);QImage image = pixmap.toImage();if (image.isNull() || image.width() < 1 || image.height() < 1) {return; }QColor color = QColor(image.pixel(0, 0));
Rectangle {anchors.fill: parentcolor: "#f0f0f0"border.color: "#cccccc"border.width: 1radius: 5ColumnLayout {anchors.fill: parentanchors.margins: 10spacing: 10Text {Layout.alignment: Qt.AlignHCentertext: "顏色提取器"font.pixelSize: 18font.bold: true}Rectangle {Layout.fillWidth: trueLayout.preferredHeight: 50color: colorPicker.isActive ? colorPicker.hexColor : "#cccccc"border.color: "#999999"border.width: 1radius: 4Text {anchors.centerIn: parenttext: colorPicker.isActive ? colorPicker.hexColor : "等待提取顏色..."color: colorPicker.isActive ? (isDarkColor(colorPicker.red, colorPicker.green, colorPicker.blue) ? "white" : "black") : "black"font.pixelSize: 14}}Text {Layout.alignment: Qt.AlignHCentertext: colorPicker.isActive ? colorPicker.rgbColor : "RGB(0, 0, 0)"font.pixelSize: 14}Button {Layout.fillWidth: trueLayout.preferredHeight: 40text: colorPicker.isActive ? "停止提取" : "開始提取"onClicked: {if (colorPicker.isActive) {colorPicker.stopPicking()} else {colorPicker.startPicking()}}}Button {Layout.fillWidth: trueLayout.preferredHeight: 30text: "退出"onClicked: {Qt.quit()}}}}
完整Demo下載