前言
实现一个简单的小工具,使用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下载