TakashiKoide
3/29/2020 - 10:35 AM

グラデーションピッカー

# -*- coding: utf-8 -*-

import sys
import math

from PySide2.QtWidgets import (QWidget,
                               QMainWindow,
                               QPushButton,
                               QDialog,
                               QApplication,
                               QVBoxLayout,
                               QGraphicsView,
                               QGraphicsScene)
from PySide2.QtCore import (Qt,
                            Signal,
                            QRect,
                            QLineF,
                            QPoint,
                            QPointF,
                            QEvent)
from PySide2.QtGui import (QColor,
                           QFont,
                           QGuiApplication,
                           QPainter,
                           QCursor,
                           QPen,
                           QBrush,
                           QPixmap,
                           QColor,
                           QGradient,
                           QLinearGradient)


class ColorPick(QMainWindow):

    getGradation = Signal(list)

    def __init__(self, parent=None):
        super(ColorPick, self).__init__(parent)

        self.setMouseTracking(True)

        rect = QApplication.desktop().screenGeometry()
        width = rect.width()
        height = rect.height()
        screen = QGuiApplication.primaryScreen()
        self.originalPixmap = screen.grabWindow(0, 0, 0, width, height)

        self.isDrag = False
        self.currentPos = None
        self.threshold = 0.05  # 前のPickとの色の差をどの程度までとるか
        self.span = 0
        self.totalLength = 0
        self.gradation = []  # [距離,R,G,B]の配列を入れる

    def mousePressEvent(self, event):
        self.isDrag = True
        self.currentPos = QCursor().pos()
        # クリックしたタイミングを0としてグラデーションをピックする
        color = self.getCurrentColor(self.currentPos)
        currentColor = (color.red(), color.green(), color.blue())
        self.gradation.append([0, currentColor])

    def mouseReleaseEvent(self, event):

        self.isDrag = False
        retVal = []

        # 正規化
        for i, item in enumerate(self.gradation):
            key = item[0] / self.totalLength
            value = item[1]
            if i != 0 and i != len(self.gradation) - 1:
                if key - retVal[-1][0] < self.span:
                    continue
                prevDiff = colorDifference(value, self.gradation[i - 1][1])
                nextDiff = colorDifference(value, self.gradation[i + 1][1])
                if prevDiff > self.threshold or nextDiff > self.threshold:
                    retVal.append([key, value])
            else:
                retVal.append([key, value])
        # マウスを話したらSignalで結果を返す
        self.getGradation.emit(retVal)

        self.close()

    def mouseMoveEvent(self, event):
        # GradColorを処理する
        if self.isDrag:
            pos = QCursor().pos()
            line = QLineF(QPointF(pos), QPointF(self.currentPos))
            # マウスの移動距離を保存(あとで正規化)
            self.totalLength += line.length()
            color = self.getCurrentColor(pos)
            currentColor = (color.red(), color.green(), color.blue())

            self.gradation.append([self.totalLength, currentColor])

            self.currentPos = pos
            self.repaint()

    def paintEvent(self, event):

        painter = QPainter()
        painter.begin(self)
        rectSize = QApplication.desktop().screenGeometry()
        painter.drawPixmap(rectSize, self.originalPixmap)

        x = QCursor().pos().x()
        y = QCursor().pos().y()
        offset = 30

        if self.isDrag:
            pen = QPen(Qt.red, 7)
            painter.setPen(pen)
            painter.drawPoint(x, y)

            color = self.getCurrentColor(QCursor().pos())
            painter.setBrush(color)
            pen = QPen(Qt.black, 1)
            painter.setPen(pen)
            rect = QRect(x + offset, y + offset, 20, 20)
            painter.drawRect(rect)

            painter.setFont(QFont(u'メイリオ', 8, QFont.Bold, False))
            pen = QPen(Qt.white, 1)
            painter.setPen(pen)
            painter.drawText(x + offset + 30, y + offset + 17, "RGB({},{},{})".format(color.red(), color.green(), color.blue()))

        painter.end()

    def getCurrentColor(self, pos):
        x = pos.x()
        y = pos.y()
        return self.originalPixmap.toImage().pixelColor(x, y)


def colorDifference(src, dst):
    # 超シンプルな色差を求める関数
    rd = (src[0] / 255.0) - (dst[0] / 255.0)
    gd = (src[1] / 255.0) - (dst[1] / 255.0)
    bd = (src[2] / 255.0) - (dst[2] / 255.0)
    return math.sqrt(rd * rd + gd * gd + bd * bd) / math.sqrt(3)



if __name__ == '__main__':
    win = ColorPick()
    win.showFullScreen()