示例#1
0
    def paintEvent(self, event):
        radius = 50

        treeSize = QSizeF(2 * radius, 2 * radius)
        bounds = QRectF((self.width() - treeSize.height()) / 2,
                        (self.height() - treeSize.width()) / 2,
                        treeSize.width(), treeSize.height())

        painter = QPainter(self)

        # draw the shadow
        painter.setBrush(Qt.black)
        painter.setPen(Qt.NoPen)
        painter.setOpacity(0.5)

        xrad = 95
        yrad = self.shadowLength * 20
        rect = QRectF(-xrad, -yrad, xrad, yrad)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.rotate(self.angle)
        painter.translate(xrad / 2, yrad / 2)
        painter.drawChord(rect, 0, 180 * 16)
        painter.resetTransform()

        # draw the tree
        painter.setOpacity(1)
        self.tree.render(painter, bounds)

        # draw the compass
        bounds = QRectF(10, 10, 50, 50)
        self.compass.render(painter, bounds)
示例#2
0
    def paintEvent(self, event):
        radius = 50
        
        treeSize = QSizeF(2 * radius, 2 * radius)
        bounds = QRectF( (self.width() - treeSize.height()) / 2,
                         (self.height() - treeSize.width()) / 2,
                         treeSize.width(),
                         treeSize.height())

        painter = QPainter(self)

        # draw the shadow
        painter.setBrush(Qt.black)
        painter.setPen(Qt.NoPen)
        painter.setOpacity(0.5)

        xrad = 95
        yrad = self.shadowLength * 20
        rect = QRectF(-xrad, -yrad, xrad, yrad)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.rotate(self.angle)
        painter.translate(xrad/2, yrad/2)
        painter.drawChord(rect, 0, 180*16)
        painter.resetTransform()

        # draw the tree
        painter.setOpacity(1)
        self.tree.render(painter, bounds)

        # draw the compass
        bounds = QRectF( 10, 10, 50, 50)
        self.compass.render(painter, bounds)
示例#3
0
    def paintEvent(self, event):
        global act_array
        super().paintEvent(event)
        painter = QPainter(self)
        for i in range(0, act_array.row*act_array.col+1):
            painter.drawRect(act_array.rec[i])
            bs = QBrush(act_array.actuator[i].color)
            painter.fillRect(act_array.rec[i], bs)

        # # 含角度显示
        for index in range(0, len(Parcels)):

            painter.resetTransform()        # 重置变换
            parcel = Parcels[index]
            rec_x = parcel.x - (parcel.l-1)/2
            rec_y = parcel.y - (parcel.w-1)/2
            parcel.rec = QRectF(rec_x, rec_y, parcel.l, parcel.w)

            theta = -parcel.theta/180*pi   # 先反方向旋转
            # 坐标y轴是反的,所以想要使用旋转矩阵需要反过来乘
            M = np.array([[cos(theta), -sin(theta)], [sin(theta), cos(theta)]])
            [rec_x2, rec_y2] = np.dot([parcel.x, parcel.y], M)
            painter.rotate(-parcel.theta)  # 坐标旋转角度
            parcel.rec = parcel.rec.translated(
                int(rec_x2-parcel.x), int(rec_y2-parcel.y))
            painter.drawRect(parcel.rec)
            bs = QBrush(QColor(255, 255, 255))
            painter.fillRect(parcel.rec, bs)

            painter.drawText(parcel.rec,str(parcel.prio))
示例#4
0
    def drawBackground(self, painter: QtGui.QPainter, rect: QtCore.QRectF):
        painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
        painter.resetTransform()
        painter.fillRect(0, 0,
                         self.size().width(),
                         self.size().height(), QtGui.QColor('darkGray'))
        global_transform = QtGui.QTransform()
        global_transform.translate(self.offsetX, self.offsetY)
        painter.setTransform(global_transform, False)

        # Draw tile layer
        tile_layer = self.map.get_tile_layer()
        if tile_layer and tile_layer.visible:
            self.draw_tiles(tile_layer.data, painter, global_transform)
        # painter.scale(self.sc, self.sc)
        # Draw layer w/ objects
        for layer in self.map.get_object_layers(only_visible=True):
            self.draw_objects(layer.get_objects(), painter)

        painter.resetTransform()
        painter.setPen(QtGui.QColor('black'))
        if self.lmbPressed:
            painter.drawRect(0 + self.mouseStartX, 0 + self.mouseStartY,
                             self.mouseCurX - self.mouseStartX,
                             self.mouseCurY - self.mouseStartY)
示例#5
0
 def paintEvent(self, event):
     painter = QPainter(self)
     if self.layer is not None:
         painter.resetTransform()
         painter.drawImage(self.rect(), self.qImage)
         self.drawShapes(painter)
     else:
         painter.eraseRect(self.rect())
示例#6
0
 def draw_cached_picture(self):
     qp = QPainter()
     geom = self.geometry()
     qp.begin(self)
     qp.resetTransform()
     qp.drawPixmap((geom.width() - self.bitmap_info.width) / 2,
                   (geom.height() - self.bitmap_info.height) / 2,
                   self.pixmap_cache)
     qp.end()
示例#7
0
    def draw_cached(self):
        qp = QPainter()
        geom = self.geometry()
        qp.begin(self)
        qp.resetTransform()

        qp.drawPixmap(
            (geom.width() - self.info.width * self.pixel_size) / 2,
            (geom.height() - abs(self.info.height) * self.pixel_size) / 2,
            self.pixmap_cache)
        qp.end()
示例#8
0
文件: _annotate.py 项目: pikers/piker
def qgo_draw_markers(
    markers: list,
    color: Color,
    p: QtGui.QPainter,
    left: float,
    right: float,
    right_offset: float,
) -> float:
    """Paint markers in ``pg.GraphicsItem`` style by first
    removing the view transform for the painter, drawing the markers
    in scene coords, then restoring the view coords.

    """
    # paint markers in native coordinate system
    orig_tr = p.transform()

    start = orig_tr.map(Point(left, 0))
    end = orig_tr.map(Point(right, 0))
    up = orig_tr.map(Point(left, 1))

    dif = end - start
    # length = Point(dif).length()
    angle = np.arctan2(dif.y(), dif.x()) * 180 / np.pi

    p.resetTransform()

    p.translate(start)
    p.rotate(angle)

    up = up - start
    det = up.x() * dif.y() - dif.x() * up.y()
    p.scale(1, 1 if det > 0 else -1)

    p.setBrush(fn.mkBrush(color))
    # p.setBrush(fn.mkBrush(self.currentPen.color()))
    tr = p.transform()

    sizes = []
    for path, pos, size in markers:
        p.setTransform(tr)

        # XXX: we drop the "scale / %" placement
        # x = length * pos
        x = right_offset

        p.translate(x, 0)
        p.scale(size, size)
        p.drawPath(path)
        sizes.append(size)

    p.setTransform(orig_tr)
    return max(sizes)
示例#9
0
 def drawBackground(self, painter: QtGui.QPainter, rect: QtCore.QRectF):
     painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
     painter.resetTransform()
     painter.fillRect(-2000, -1000, 4000, 2000, QtGui.QColor('darkGray'))
     globalTransform = QtGui.QTransform()
     globalTransform.translate(self.offsetX, self.offsetY)
     painter.setTransform(globalTransform, False)
     for y in range(len(self.map.tiles)):
         for x in range(len(self.map.tiles[y])):
             painter.scale(self.sc, self.sc)
             painter.translate(x * self.map.gridSize, y * self.map.gridSize)
             if self.map.tiles[y][x].rotation == 90:
                 painter.rotate(90)
                 painter.translate(0, -self.map.gridSize)
             elif self.map.tiles[y][x].rotation == 180:
                 painter.rotate(180)
                 painter.translate(-self.map.gridSize, -self.map.gridSize)
             elif self.map.tiles[y][x].rotation == 270:
                 painter.rotate(270)
                 painter.translate(-self.map.gridSize, 0)
             painter.drawImage(
                 QtCore.QRectF(0, 0, self.map.gridSize, self.map.gridSize),
                 self.tileSprites[self.map.tiles[y][x].kind])
             if self.tileSelection[0] <= x < self.tileSelection[2] and self.tileSelection[1] <= y < \
                     self.tileSelection[3]:
                 painter.setPen(QtGui.QColor('green'))
                 painter.drawRect(
                     QtCore.QRectF(1, 1, self.map.gridSize - 1,
                                   self.map.gridSize - 1))
             else:
                 painter.setPen(QtGui.QColor('white'))
                 painter.drawRect(
                     QtCore.QRectF(0, 0, self.map.gridSize,
                                   self.map.gridSize))
             painter.setTransform(globalTransform, False)
     # painter.scale(self.sc, self.sc)
     if self.map.items:
         for s in self.map.items:
             if self.objects.__contains__(s.kind):
                 painter.drawImage(
                     QtCore.QRectF(
                         self.map.gridSize * self.sc * s.position['x'],
                         self.map.gridSize * self.sc * s.position['y'],
                         self.map.gridSize * self.sc / 2,
                         self.map.gridSize * self.sc / 2),
                     self.objects[s.kind])
     painter.resetTransform()
     painter.setPen(QtGui.QColor('black'))
     if self.lmbPressed:
         painter.drawRect(0 + self.mouseStartX, 0 + self.mouseStartY,
                          self.mouseCurX - self.mouseStartX,
                          self.mouseCurY - self.mouseStartY)
示例#10
0
    def paintEvent(self, event):
        painter = QPainter(self)
        palette = self.palette()
        midColor = palette.mid().color()
        highlight = palette.highlight().color()

        # background
        painter.fillRect(self.rect(), midColor.lighter())

        # float rect
        color = highlight if self.mouseHoverState == MOUSE_HOVER.HOVER_FLOAT else midColor
        painter.setPen(color)
        painter.setBrush(palette.light())
        painter.drawRect(self.floatRect)
        painter.setBrush(highlight if color == highlight else midColor)
        painter.drawRect(self.floatRect.adjusted(4, 2, -2, -4))

        # hsplit rect
        color = highlight if self.mouseHoverState == MOUSE_HOVER.HOVER_HSPLIT else midColor
        painter.setPen(color)
        painter.setBrush(palette.light())
        painter.drawRect(self.hSplitRect)
        painter.setBrush(highlight if color == highlight else midColor)
        painter.drawRect(self.hSplitRect.adjusted(2, 2, -6, -2))

        # float rect
        color = highlight if self.mouseHoverState == MOUSE_HOVER.HOVER_VSPLIT else midColor
        painter.setPen(color)
        painter.setBrush(palette.light())
        painter.drawRect(self.vSplitRect)
        painter.setBrush(highlight if color == highlight else midColor)
        painter.drawRect(self.vSplitRect.adjusted(2, 2, -2, -6))

        # float rect
        color = highlight if self.mouseHoverState == MOUSE_HOVER.HOVER_CLOSE else midColor
        painter.setPen(color)
        painter.setBrush(palette.light())
        painter.drawRect(self.closeRect)
        painter.translate(self.closeRect.topLeft())
        painter.setPen(QPen(color, 1.5))
        painter.drawLine(QPoint(4, 4), QPoint(9, 9))
        painter.drawLine(QPoint(4, 9), QPoint(9, 4))
        painter.resetTransform()
示例#11
0
def draw_filter_covariance_ellipse(painter: QPainter, x, y, cov_x, cov_y,
                                   heading):
    pen = QPen()
    pen.setStyle(Qt.SolidLine)
    pen.setBrush(SETTINGS["COLOR_FILTER_TRACE"])
    pen.setWidth(2)
    painter.setPen(pen)
    painter.setBrush(Qt.white)

    heading = math.degrees(heading)

    painter.translate(x, y)
    painter.rotate(heading)

    # scaling
    cov_x *= SETTINGS["COV_SCALING"]
    cov_y *= SETTINGS["COV_SCALING"]

    rect = QtCore.QRect(-cov_x / 2, -cov_y / 2, cov_x, cov_y)
    painter.drawEllipse(rect)

    painter.resetTransform()
示例#12
0
 def paint_gl(self, window_size: QSize, camera: Camera, painter: QPainter,
              hover: bool) -> None:
     GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
     painter.setRenderHint(QPainter.HighQualityAntialiasing)
     painter.setPen(self.pen)
     cp = (
         CanvasPos(self.left, self.top),
         CanvasPos(self.right, self.top),
         CanvasPos(self.right, self.bottom),
         CanvasPos(self.left, self.bottom),
     )
     ws = window_size
     scale = 0.5 * camera.zoom * ws.width()
     if hover:
         self.pen.setWidthF(3.0 / scale)
         self.pen.setColor(QColor(0x40, 0xA0, 0xFF, 0x90))
     else:
         self.pen.setWidthF(2.5 / scale)
         self.pen.setColor(QColor(0x40, 0x90, 0xFF, 0x70))
     painter.setPen(self.pen)
     painter.resetTransform()
     painter.translate(0.5 * ws.width(), 0.5 * ws.height())
     painter.translate(-camera.center.x * scale, -camera.center.y * scale)
     painter.scale(scale, scale)
     x, y = cp[0].x, cp[0].y
     w, h = cp[1].x - cp[0].x, cp[3].y - cp[0].y
     rectangle = QtCore.QRectF(x, y, w, h)
     painter.drawRect(rectangle)
     outer_rect = QtCore.QRectF(x - 2, y - 2, w + 4, h + 4)
     # darken everything beyond edge
     outer1 = QPainterPath()
     outer1.addRect(outer_rect)
     outer1.addRect(rectangle)
     if hover:
         painter.fillPath(outer1, QColor(0x20, 0x40, 0x80, 0x50))
     else:
         painter.fillPath(outer1, QColor(0x20, 0x40, 0x80, 0x90))
示例#13
0
    def paintEvent(self, event):
        p = QPainter(self)
        r: QRect = event.rect()

        for i in self.texEnums:

            p.resetTransform()

            if isinstance(i, BaseBlock):
                p.translate(r.width() / 2, r.height() / 2)
                if i.direction == 90 or i.direction == 270:
                    r.setRect(0, 0, r.height(), r.width())
                p.rotate(i.direction)
                p.translate(-r.width() / 2, -r.height() / 2)
                p.drawImage(r, self.imgs[i.getDrawable()])
                if i.color != EColor.none:
                    if not self.drawFullColor:
                        p.setOpacity(0.6)
                        p.drawImage(r, self.masks[i.color][i.getDrawable()])
                        p.setOpacity(1)
                    else:
                        p.drawImage(r, self.masks[i.color][i.getDrawable()])
            else:
                p.drawImage(r, self.imgs[i])
示例#14
0
 def drawBackground(self, p: QPainter, rect: QRectF):
     p.save()
     p.resetTransform()
     p.drawTiledPixmap(self.viewport().rect(),
                       self.backgroundBrush().texture())
     p.restore()
    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter()
        painter.begin(self)

        # background
        brushBG = QBrush(Qt.black, Qt.SolidPattern)
        if not common.AppSettings["ShowMask"]:
            brushBG.setColor(Qt.darkGray)
            brushBG.setStyle(Qt.Dense1Pattern)
            painter.setBackground(Qt.gray)
        else:
            brushBG.setColor(Qt.black)
            brushBG.setStyle(Qt.SolidPattern)
            painter.setBackground(Qt.black)
        painter.setBackgroundMode(Qt.OpaqueMode)
        painter.setBrush(brushBG)
        painter.setPen(Qt.NoPen)
        painter.drawRect(0, 0, self.width(), self.height())

        # draw photo
        if not self.myPhoto.isNull():
            # rotate and draw photo as specified by user
            transform = QTransform()
            transform.translate(self.myPhotoDestRect.center().x(), self.myPhotoDestRect.center().y())
            transform.rotate(-self.myPhotoRotation)
            transform.translate(-self.myPhotoDestRect.center().x(), -self.myPhotoDestRect.center().y())
            painter.setTransform(transform)
            painter.drawImage(self.myPhotoDestRect, self.myPhoto, self.myPhotoSrcRect) # draw it
            painter.resetTransform()

            # useful local vars
            centerPoint = QPoint(self.viewCenter[0], self.viewCenter[1])
            destRect = QRect(0, 0, self.myPhotoDestRect.width(), self.myPhotoDestRect.height())
            fontWidth = self.fontMetrics.width("X")

            # mask
            if common.AppSettings["ShowMask"]:
                maskPainter = QPainter()
                maskPainter.begin(self.mask)
                maskPainter.setBrush(QBrush(Qt.magenta, Qt.SolidPattern))
                maskPainter.drawEllipse(self.viewCenter[0] - self.myPhotoRadius, self.viewCenter[1] - self.myPhotoRadius, self.myPhotoDiameter, self.myPhotoDiameter)
                maskPainter.end()
                painter.setCompositionMode(QPainter.CompositionMode_DestinationIn)
                painter.drawImage(0, 0, self.mask)
                painter.setCompositionMode(QPainter.CompositionMode_SourceOver)

            # HUD
            if common.AppSettings["ShowHUD"]:
                painter.setBackgroundMode(Qt.TransparentMode)
                #painter.setBackground(Qt.black)
                painter.setBrush(Qt.NoBrush)
                painter.setFont(self.fontScaled)

                # draw UV grid
                if common.AppSettings["ShowUVGrid"]:
                    painter.setPen(self.penText)
                    # box
                    tl = self.myPhotoTopLeft
                    tr = (self.viewCenter[0] + self.myPhotoRadius, self.viewCenter[1] - self.myPhotoRadius)
                    bl = (self.viewCenter[0] - self.myPhotoRadius, self.viewCenter[1] + self.myPhotoRadius)
                    br = (self.viewCenter[0] + self.myPhotoRadius, self.viewCenter[1] + self.myPhotoRadius)
                    painter.drawLine(tl[0], tl[1], tr[0], tr[1])
                    painter.drawLine(bl[0], bl[1], br[0], br[1])
                    painter.drawLine(tl[0], tl[1], bl[0], bl[1])
                    painter.drawLine(tr[0], tr[1], br[0], br[1])
                    # crosshairs
                    painter.drawLine(tl[0], self.viewCenter[1], tr[0], self.viewCenter[1])
                    painter.drawLine(self.viewCenter[0], tr[1], self.viewCenter[0], br[1])
                    # labels
                    destRect.setCoords(tl[0] + 4, tl[1] + 4, self.width(), self.height())
                    painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "0")
                    destRect.setCoords(tr[0] - (fontWidth+4), tr[1] + 4, self.width(), self.height())
                    painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "1")
                    destRect.setCoords(bl[0] + 3, bl[1] - (self.fontMetrics.height()+3), self.width(), self.height())
                    painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "1")
                    destRect.setCoords(br[0] - (fontWidth+3), br[1] - (self.fontMetrics.height()+3), self.width(), self.height())
                    painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "1")
                    # grid coordinates
                    gpntrad = self.myPhotoRadius * 0.005
                    painter.setPen(self.penText)
                    painter.setBrush(self.brushGrid)
                    painter.setFont(self.fontScaled)
                    for i in range(0, len(self.gridpoints)):
                        point = self.gridpoints[i]
                        u, v = self.gridUVs[i]
                        t, p = self.gridskycoords[i]
                        painter.drawEllipse(QPoint(point[0], point[1]), gpntrad, gpntrad)
                        destRect.setCoords(point[0]+fontWidth/2, point[1]-self.fontMetrics.height(), self.width(), self.height())
                        textuv = "{0:.1f}u, {1:.1f}v".format(round(u,1), round(v,1))
                        painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, textuv)
                        destRect.setCoords(point[0]+fontWidth/2, point[1], self.width(), self.height())
                        textuv = "{0:d}°, {1:d}°".format(int(round(t)), int(round(p)))
                        painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, textuv)
                    painter.setBrush(Qt.NoBrush)

                # draw lens warp
                if common.AppSettings["ShowLensWarp"]:
                    # ideal lens longitudes along azimuth
                    painter.setPen(self.penText)
                    for i in range(0, int(len(self.compassTicks)/2), 3):
                        p1 = QPoint(self.compassTicks[i][2], self.compassTicks[i][3])
                        p2 = QPoint(self.compassTicks[i+18][2], self.compassTicks[i+18][3])  # tick opposite 180 degrees
                        painter.drawLine(p1, p2)
                    # ideal lens latitudes along zenith
                    for r, alt in self.lensIdealRadii:
                        painter.drawEllipse(centerPoint, r, r)
                    # actual/warped lens latitudes along zenith
                    painter.setPen(self.penLens)
                    for r, alt in self.lensRealRadii:
                        painter.drawEllipse(centerPoint, r, r)
                        destRect.setCoords(self.viewCenter[0] + r + 3, self.viewCenter[1] - (self.fontMetrics.height() + 3), self.width(), self.height())
                        painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "{0:d}°".format(int(alt)))

                # draw compass
                if common.AppSettings["ShowCompass"]:
                    # compass ticks text shadows
                    if common.AppSettings["ShowShadows"]:
                        painter.setPen(self.penShadowText)
                        for tick in self.compassTicks:
                            destRect.setCoords(tick[4] + 1, tick[5] + 1, self.width(), self.height())
                            painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(tick[6])+"°")
                    # compass ticks text
                    painter.setPen(self.penText)
                    for tick in self.compassTicks:
                        painter.drawLine(tick[0], tick[1], tick[2], tick[3])
                        destRect.setCoords(tick[4], tick[5], self.width(), self.height())
                        painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(tick[6])+"°")
                    # photo radius
                    #painter.drawEllipse(self.viewCenter[0] - self.myPhotoRadius, self.viewCenter[1] - self.myPhotoRadius, self.myPhotoDiameter, self.myPhotoDiameter)
                    painter.drawEllipse(centerPoint, self.myPhotoRadius, self.myPhotoRadius)
                    # cardinal directions
                    destRect.setCoords(self.viewCenter[0] - self.myPhotoRadius - (fontWidth+4), self.viewCenter[1] - self.fontMetrics.height()/2, self.width(), self.height())
                    painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "W")
                    destRect.setCoords(self.viewCenter[0] + self.myPhotoRadius + 4, self.viewCenter[1] - self.fontMetrics.height()/2, self.width(), self.height())
                    painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "E")
                    destRect.setCoords(self.viewCenter[0] - fontWidth/2, self.viewCenter[1] - self.myPhotoRadius - (self.fontMetrics.height()+3), self.width(), self.height())
                    painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "S")
                    destRect.setCoords(self.viewCenter[0] - fontWidth/2, self.viewCenter[1] + self.myPhotoRadius + 3, self.width(), self.height())
                    painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "N")

                # draw sampling pattern
                if common.AppSettings["ShowSamples"]:
                    painter.setPen(self.penText)
                    for i, points in enumerate(self.sampleAreaVisible):
                        painter.drawLine(QLine(points[0], points[1]))
                        painter.drawLine(QLine(points[1], points[2]))
                        painter.drawLine(QLine(points[2], points[3]))
                        painter.drawLine(QLine(points[3], points[0]))
                    for i in range(0, len(self.samplePoints)):
                        p = self.samplePoints[i]
                        painter.drawEllipse(QPoint(p[0],p[1]), ViewFisheye.SampleRadius, ViewFisheye.SampleRadius)
                        painter.drawText(p[0] + ViewFisheye.SampleRadius, p[1], str(i))

                # draw sun path
                if common.AppSettings["ShowSunPath"]:
                    sunradius = self.myPhotoRadius * 0.1
                    # shadows
                    painter.setPen(self.penShadowSun)
                    if common.AppSettings["ShowShadows"]:
                        painter.drawEllipse(QPoint(self.sunPositionVisible[0]+1, self.sunPositionVisible[1]+1), sunradius, sunradius)
                        self.pathSun.translate(1.0, 1.0)
                        painter.drawPath(self.pathSun)
                        self.pathSun.translate(-1.0, -1.0)
                        for i in range(0, self.pathSun.elementCount()):
                            e = self.pathSun.elementAt(i)
                            destRect.setCoords(e.x, e.y + self.fontMetrics.height()/2 + 1, self.width(), self.height())
                            painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(self.sunPathPoints[i][2].hour))
                    # sun, path, hours
                    painter.setPen(self.penSun)
                    painter.drawEllipse(QPoint(self.sunPositionVisible[0], self.sunPositionVisible[1]), sunradius, sunradius)
                    painter.drawPath(self.pathSun)
                    for i in range(0, self.pathSun.elementCount()):
                        e = self.pathSun.elementAt(i)
                        destRect.setCoords(e.x, e.y + self.fontMetrics.height() / 2, self.width(), self.height())
                        painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(self.sunPathPoints[i][2].hour))

                # draw selected samples (ALWAYS)
                r = QRect()
                # shadows
                if common.AppSettings["ShowShadows"]:
                    painter.setPen(self.penShadowSelected)
                    for i in self.samplesSelected:
                        x, y = self.samplePoints[i]
                        painter.drawEllipse(QPoint(x+1, y+1), ViewFisheye.SampleRadius, ViewFisheye.SampleRadius)
                # samples
                for i in self.samplesSelected:
                    painter.setPen(self.penSelected[i])
                    x, y = self.samplePoints[i]
                    painter.drawEllipse(QPoint(x, y), ViewFisheye.SampleRadius, ViewFisheye.SampleRadius)

                # draw user's selection bounds
                if (abs(self.dragSelectRect.right()-self.dragSelectRect.left()) >= ViewFisheye.SelectionRectMin and
                    abs(self.dragSelectRect.bottom()-self.dragSelectRect.top()) >= ViewFisheye.SelectionRectMin):
                    painter.setPen(self.penSelectRect)
                    painter.drawRect(self.dragSelectRect)

                # draw timestamp
                painter.setPen(self.penText)
                painter.setFont(self.fontFixed)
                destRect.setCoords(10, 10, self.width() / 2, 50)
                painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, str(self.myPhotoTime))
                # draw sky cover assessment
                destRect.setCoords(10, 25, self.width(), self.height())
                painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, self.skyCover.name + "/" + common.SkyCoverDesc[self.skyCover])
                # draw photo rotation
                if self.myPhotoRotation != 0:
                    destRect.setCoords(10, self.height()-25, self.width(), self.height())
                    painter.drawText(destRect, Qt.AlignTop | Qt.AlignLeft, "Rotation: " + str(self.myPhotoRotation) + "°")

                # where is the mouse relative to the center?
                # this is used as an optimization to only display information when mouse is in fisheye portion
                dx = self.coordsMouse[0] - self.viewCenter[0]
                dy = self.coordsMouse[1] - self.viewCenter[1]
                distance = math.sqrt((dx * dx) + (dy * dy))  # distance from mouse to view center

                # coordinates we are interested in
                #self.coordsMouse    # x,y of this widget
                coordsxy = (-1, -1)  # x,y over photo as scaled/rendered on this widget
                coordsXY = (-1, -1)  # x,y over actual original photo on disk
                coordsUV = (-1, -1)  # u,v coords of fisheye portion of photo w/ 0,0 top left and 1,1 bottom right
                coordsTP = (-1, -1)  # theta,phi polar coordinates
                # text
                textxy = "-1, -1 xy"
                textXY = "-1, -1 xy"
                textUV = "-1, -1 uv"
                textTP = "-1, -1 θφ"
                textPX = "0 0 0 px"

                # compute all relevant information only when mouse is within fisheye portion of photo
                if distance < self.myPhotoRadius:
                    coordsxy = (self.coordsMouse[0] - self.myPhotoDestRect.x(),
                                self.coordsMouse[1] - self.myPhotoDestRect.y())
                    coordsXY = (int(coordsxy[0] / self.myPhotoDestRect.width() * self.myPhoto.width()),
                                int(coordsxy[1] / self.myPhotoDestRect.height() * self.myPhoto.height()))
                    coordsUV = ((self.coordsMouse[0] - self.myPhotoTopLeft[0]) / self.myPhotoDiameter,
                                (self.coordsMouse[1] - self.myPhotoTopLeft[1]) / self.myPhotoDiameter)
                    coordsTP = utility_angles.FisheyeUV2SkyCoord(coordsUV[0], coordsUV[1])
                    # text
                    textxy = str(coordsxy[0]) + ", " + str(coordsxy[1]) + " xy"
                    textXY = str(coordsXY[0]) + ", " + str(coordsXY[1]) + " xy"
                    textUV = "{:.2f}".format(coordsUV[0]) + ", " + "{:.2f}".format(coordsUV[1]) + " uv"
                    textTP = "{:.2f}".format(coordsTP[0]) + ", " + "{:.2f}".format(coordsTP[1]) + " θφ"

                # pixels colors
                pixreg = common.AppSettings["PixelRegion"]
                colorsRegion = np.zeros((pixreg, pixreg, 4))
                colorFinal = colorsRegion[0,0]  # RGBA of pixel under mouse of photo on disk
                # colorFinal = self.myPhoto.pixelColor(coordsXY[0], coordsXY[1])
                if distance < self.myPhotoRadius:
                    halfdim = int(pixreg / 2)
                    rstart = coordsXY[1]-halfdim
                    rstop = coordsXY[1]+halfdim+1
                    cstart = coordsXY[0]-halfdim
                    cstop = coordsXY[0]+halfdim+1
                    if (rstart >= 0 and rstop<=self.myPhotoPixels.shape[0] and
                        cstart >= 0 and cstop<=self.myPhotoPixels.shape[1]):
                        colorsRegion = self.myPhotoPixels[rstart:rstop, cstart:cstop]
                        colorFinal = colorsRegion[halfdim, halfdim]
                        if pixreg > 1:  # with pixel weighting
                            colorFinal = utility_data.collectPixels([coordsXY], [pixreg], pixels=self.myPhotoPixels, weighting=common.PixelWeighting(common.AppSettings["PixelWeighting"]))[0]
                    textPX = str(colorFinal[0]) + " " + str(colorFinal[1]) + " " + str(colorFinal[2]) + " px"

                # draw HUD text strings
                # x,y coords
                destRect.setCoords(0, 0, self.width() - 10, self.height()- 124)
                painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textxy)
                # X,Y coords
                destRect.setCoords(0, 0, self.width() - 10, self.height() - 114)
                painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textXY)
                # u,v coords
                destRect.setCoords(0, 0, self.width() - 10, self.height() - 104)
                painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textUV)
                # t,p coords
                destRect.setCoords(0, 0, self.width() - 10, self.height() - 94)
                painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textTP)
                # pixel color
                destRect.setCoords(0, 0, self.width() - 10, self.height() - 84)
                painter.drawText(destRect, Qt.AlignBottom | Qt.AlignRight, textPX)

                # compute pixel visualization coordinates
                circleX = self.width() - 10 - ViewFisheye.SelectedPixelBox - 10 - ViewFisheye.SelectedPixelBox - 10 - ViewFisheye.SelectedPixelBox
                circleY = self.height() - 10 - ViewFisheye.SelectedPixelBox
                pixelsX = self.width() - 10 - ViewFisheye.SelectedPixelBox - 10 - ViewFisheye.SelectedPixelBox
                pixelsY = self.height() - 10 - ViewFisheye.SelectedPixelBox
                pixelsWeightedX = self.width() - ViewFisheye.SelectedPixelBox - 10
                pixelsWeightedY = self.height() - 10 - ViewFisheye.SelectedPixelBox

                # draw pixel visualization - fills
                pixreg = common.AppSettings["PixelRegion"]
                if distance < self.myPhotoRadius:
                    painter.setPen(Qt.NoPen)
                    # pixel region
                    pixdim = ViewFisheye.SelectedPixelBox / pixreg
                    for row in range(0, pixreg):
                        for col in range(0, pixreg):
                            color = colorsRegion[row, col]
                            color = QColor(color[0], color[1], color[2])
                            painter.setBrush(QBrush(color, Qt.SolidPattern))
                            painter.drawRect(pixelsX + (col * pixdim), pixelsY + (row * pixdim), math.ceil(pixdim), math.ceil(pixdim))
                    # final pixel color
                    color = QColor(colorFinal[0], colorFinal[1], colorFinal[2])
                    painter.setBrush(QBrush(color, Qt.SolidPattern))
                    cx = circleX + (coordsUV[0] * ViewFisheye.SelectedPixelBox)
                    cy = circleY + (coordsUV[1] * ViewFisheye.SelectedPixelBox)
                    painter.drawEllipse(cx - 5, cy - 5, 10, 10)
                    painter.drawRect(pixelsWeightedX, pixelsWeightedY, ViewFisheye.SelectedPixelBox, ViewFisheye.SelectedPixelBox)

                # draw pixel visualization - outlines
                painter.setPen(self.penText)
                painter.setBrush(Qt.NoBrush)
                painter.drawEllipse(circleX, circleY, ViewFisheye.SelectedPixelBox, ViewFisheye.SelectedPixelBox)
                painter.drawRect(pixelsX, pixelsY, ViewFisheye.SelectedPixelBox, ViewFisheye.SelectedPixelBox)
                painter.drawRect(pixelsWeightedX, pixelsWeightedY, ViewFisheye.SelectedPixelBox, ViewFisheye.SelectedPixelBox)

                # raw data missing indicator
                # if (not self.rawAvailable):
                #     painter.drawPixmap(pixelX + ViewFisheye.SelectedPixelBox / 2,
                #                        pixelY + ViewFisheye.SelectedPixelBox / 2,
                #                        self.iconWarning)

        # end draw
        painter.end()
示例#16
0
   def paintEvent(self,event):  #在窗口上绘图
      painter=QPainter(self)
      painter.setRenderHint(QPainter.Antialiasing)
      painter.setRenderHint(QPainter.TextAntialiasing)


##生成五角星的5个顶点的,假设原点在五角星中心
      R=100.0        #半径
      Pi=3.14159     #常数
      deg=Pi*72.0/180   
      points=[QPoint(R,0),
              QPoint(R*math.cos(deg),    -R*math.sin(deg)),
              QPoint(R*math.cos(2*deg),  -R*math.sin(2*deg)),
              QPoint(R*math.cos(3*deg),  -R*math.sin(3*deg)),
              QPoint(R*math.cos(4*deg),  -R*math.sin(4*deg)) ]   #元组数据

      font=painter.font()
      font.setPointSize(14)
      font.setBold(False)
      painter.setFont(font)

   #设置画笔
      pen=QPen()
      pen.setWidth(2)   #线宽
      pen.setColor(Qt.blue)      #划线颜色
      pen.setStyle(Qt.SolidLine) #线的类型,实线、虚线等
      pen.setCapStyle(Qt.FlatCap)      #线端点样式
      pen.setJoinStyle(Qt.BevelJoin)   #线的连接点样式
      painter.setPen(pen)
      
##设置画刷
      brush=QBrush()
      brush.setColor(Qt.yellow)        #画刷颜色
      brush.setStyle(Qt.SolidPattern)  #填充样式
      painter.setBrush(brush)

##设计绘制五角星的PainterPath,以便重复使用
      starPath=QPainterPath()
      starPath.moveTo(points[0])
      starPath.lineTo(points[2])
      starPath.lineTo(points[4])
      starPath.lineTo(points[1])
      starPath.lineTo(points[3])
      starPath.closeSubpath()    #闭合路径,最后一个点与第一个点相连

      
      starPath.addText(points[0],font,"0") #显示端点编号
      starPath.addText(points[1],font,"1")
      starPath.addText(points[2],font,"2")
      starPath.addText(points[3],font,"3")
      starPath.addText(points[4],font,"4")

##绘图
      painter.save()    #保存坐标状态
      painter.translate(100,120)
      painter.drawPath(starPath)    #画星星
      painter.drawText(0,0,"S1")
      painter.restore()    #恢复坐标状态

      painter.translate(300,120)    #平移
      painter.scale(0.8,0.8)        #缩放
      painter.rotate(90)         #顺时针旋转
      painter.drawPath(starPath) #画星星
      painter.drawText(0,0,"S2")

      painter.resetTransform()      #复位所有坐标变换
      painter.translate(500,120)    #平移
      painter.rotate(-145)          #逆时针旋转
      painter.drawPath(starPath)    #画星星
      painter.drawText(0,0,"S3")    
示例#17
0
    def paint(self, p: QPainter):
        # hack
        old = self
        self = self.parent

        blockSize = self._blocksize()
        width = Ruler.Width
        xx = int(self.viewOrigin[0] / blockSize) * blockSize
        yy = int(self.viewOrigin[1] / blockSize) * blockSize
        sx, sy = self.deltaxy()
        smallstep = blockSize if blockSize > width * 5 else width * 5 // blockSize * blockSize + blockSize
        optX = QtCore.Qt.AlignmentFlag.AlignVCenter | QtCore.Qt.AlignmentFlag.AlignLeft
        optY = QtCore.Qt.AlignmentFlag.AlignVCenter | QtCore.Qt.AlignmentFlag.AlignRight

        p.save()
        p.setPen(Ruler.BorderPen)
        p.setFont(QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.SystemFont.FixedFont))

        p.fillRect(0, 0, width, self.height(), Ruler.Background)
        for y in range(0, self.height() + blockSize, blockSize):
            old._drawGrid(sx, y + sy, blockSize, p)
            iy = int((y - yy) / blockSize)
            iy == old.currentXY[1] and p.fillRect(0, y + sy, width, blockSize, Ruler.Cursor)
            iy in old.hlines and old._drawLine(width, y + sy, True, blockSize, p)

            if (y - yy) % smallstep != 0:
                p.drawLine(0, y + sy, width / 4, y + sy)
                continue
            y = y + sy
            p.drawLine(0, y, width, y)
            p.translate(0, y + smallstep)
            p.rotate(-90)
            p.drawText(QtCore.QRect(0, 0, smallstep - 1, width), optY, str(iy))
            p.resetTransform()
        p.drawLine(width, 0, width, self.height())

        p.fillRect(0, 0, self.width(), width, Ruler.Background)
        for x in range(0, self.width() + blockSize, blockSize):
            # old._drawGrid(sx + x, sy, False, blockSize, p)
            # x + sx: on-canvas x coord
            if x + sx < width:
                continue
            ix = int((x - xx) / blockSize)
            ix == old.currentXY[0] and p.fillRect(x + sx, 0, blockSize, width, Ruler.Cursor)
            ix in old.vlines and old._drawLine(x + sx, width, False, blockSize, p)

            if (x - xx) % smallstep != 0:
                p.drawLine(x + sx, 0, x + sx, width / 4)
                continue
            x = x + sx
            p.drawLine(x, 0, x, width)
            p.drawText(QtCore.QRect(x + 1, 0, smallstep, width), optX, str(ix))
        p.drawLine(width, width, self.width(), width)

        p.drawLine(width, 0, width, width)
        p.drawLine(0, width, width, width)
        p.fillRect(0, 0, width, width, Ruler.Corner)

        p.drawRect(0, 0, self.width() - 1, self.height() - 1)

        p.restore()
示例#18
0
class DrawingWidget(QWidget):
    def __init__(self, scale=10, a=1.0, b=1.0, c=0.0, d=1.0):
        super().__init__()

        self.a, self.b, self.c, self.d = a, b, c, d
        self.scale_x, self.scale_y = scale, 0
        self.width, self.height = 0, 0
        self.dx, self.dy = 0, 0
        self.mouse_click_x = -1
        self.mouse_click_y = -1
        self.qp = QPainter()

        self.initUI()

    def initUI(self):
        self.setGeometry(150, 150, 900, 900)
        # self.timer = QBasicTimer()
        # self.timer.start(15, self)
        self.setWindowTitle('Drawing')
        self.show()

    def paintEvent(self, event):
        self.qp.setPen(Qt.black)
        self.qp.begin(self)

        self.draw()
        self.qp.end()

    def resizeEvent(self, event):
        new_width = event.size().width()
        new_height = event.size().height()
        self.width = new_width
        self.height = new_height
        self.scale_y = self.scale_x  # new_width * 6 / new_height

    def draw(self):
        # self.draw_parabola()
        # self.draw_parabola_dists()
        self.draw_parabola_deltas()
        self.draw_axes()

    def draw_axes(self):
        a_, b_, c_, d_ = self.a, self.b, self.c, self.d
        if a_ < 0:
            self.qp.scale(-1.0, 1.0)
            a_ = -a_
            c_ = -c_

        dx = self.get_screen_x(0) - self.get_screen_x(c_)
        dy = self.get_screen_y(d_ - b_) - self.get_screen_y(0)
        self.qp.setPen(Qt.black)
        self.qp.translate(dx, dy)

        self.qp.drawLine(-self.width / 2 - dx, 0, self.width / 2 - dx, 0)
        self.qp.drawLine(0, -self.height / 2 - dy, 0, self.height / 2 - dy)

    def draw_parabola_dists(self):
        self.qp.setPen(Qt.darkBlue)
        self.qp.resetTransform()
        self.qp.translate(self.width / 2, self.height / 2)
        self.qp.scale(1.0, -1.0)

        a_, c_ = self.a, self.c
        if a_ == 0:
            self.qp.drawLine(c_, self.height, c_, -self.height)
            return
        elif a_ < 0:
            self.qp.scale(-1.0, 1.0)
            a_ = -a_

        bound = self.width
        f = self.get_screen_x(1 / (4 * a_)) - self.get_screen_x(0)
        x, y = 0, 0
        self.qp.drawPoint(x, y)

        while x <= bound:
            d1 = (f - x)**2 + (-(y + 1))**2 - (-f - x)**2
            min_d = abs(d1)
            n_x, n_y = x, y + 1

            d2 = (f - (x + 1))**2 + (-(y + 1))**2 - (-f - (x + 1))**2
            if abs(d2) < min_d:
                n_x, n_y = x + 1, y + 1
                min_d = abs(d2)

            d3 = (f - (x + 1))**2 + (-y)**2 - (-f - (x + 1))**2
            if abs(d3) < min_d:
                n_x, n_y = x + 1, y

            self.qp.drawPoint(n_x, n_y)
            self.qp.drawPoint(n_x, -n_y)
            x, y = n_x, n_y

    def draw_parabola_deltas(self):
        self.qp.setPen(Qt.red)
        self.qp.resetTransform()
        self.qp.translate(self.width / 2, self.height / 2)
        self.qp.scale(1.0, -1.0)

        a_, c_ = self.a, self.c
        if a_ == 0:
            self.qp.drawLine(c_, self.height, c_, -self.height)
            return
        elif a_ < 0:
            self.qp.scale(-1.0, 1.0)
            a_ = -a_

        bound = self.width
        p = self.get_screen_x(1 / (2 * a_)) - self.get_screen_x(0)
        x, y = 0, 0
        self.qp.drawPoint(x, y)

        p2 = 2 * p
        while x <= bound:
            delta = (y + 1) * (y + 1) - p2 * (x + 1)
            if delta < 0:
                other = delta + p2
                if abs(delta) < abs(other):
                    x, y = x + 1, y + 1
                else:
                    x, y = x, y + 1
            else:
                other = delta - 2 * y - 1
                if abs(delta) < abs(other):
                    x, y = x + 1, y + 1
                else:
                    x, y = x + 1, y

            self.qp.drawPoint(x, y)
            self.qp.drawPoint(x, -y)

    def draw_parabola(self):
        self.qp.setPen(Qt.black)
        self.qp.resetTransform()
        self.qp.translate(self.width / 2, self.height / 2)
        self.qp.scale(1.0, -1.0)

        a_, b_, c_, d_ = self.a, self.b, self.c, self.d
        if a_ == 0:
            self.qp.drawLine(c_, self.height, c_, -self.height)
            return
        elif a_ < 0:
            self.qp.scale(-1.0, 1.0)
            a_ = -a_
            c_ = -c_

        bound = self.width
        p = self.get_screen_x(1 / (2 * a_)) - self.get_screen_x(0)

        p2 = 2 * p
        p4 = 2 * p2
        x, y = 0, 0
        d = 1 - p

        while (y < p) and (x <= bound):
            self.qp.drawPoint(x, y)
            self.qp.drawPoint(x, -y)
            if d >= 0:
                x += 1
                d -= p2
            y += 1
            d += (2 * y + 1)

        if d == 1:
            d = 1 - p4
        else:
            d = 1 - p2

        # self.qp.drawLine(x, 0, x, y)
        while x <= bound:
            self.qp.drawPoint(x, y)
            self.qp.drawPoint(x, -y)
            if d <= 0:
                y += 1
                d += 4 * y
            x += 1
            d -= p4

    def get_screen_x(self, x):
        return ((self.scale_x / 2 + x) / self.scale_x) * self.width

    def get_screen_y(self, y):
        return ((self.scale_y / 2 + y) / self.scale_y) * self.height

    def timerEvent(self, event):
        self.a += 0.15
        if self.a > 10:
            self.a = -10

        self.repaint()
示例#19
0
class QtRenderer(Renderer):
    """An implementation of :class:`~renderer.Renderer` for PyQt5.
       
       This renderer will draw on any `QPaintDevice`
    """
    def __init__(self, paint_device):
        """Creates a new renderer based on a QPaintDevice pd"""
        self._grid_pen = QPen(QColor(0x808080))
        self._grid_pen.setStyle(Qt.DashLine)
        self._painter = None
        Renderer.__init__(self, paint_device)

    def set_canvas(self, canvas):
        """Tell the renderer to draw on canvas
        The type of canvas is implementation-dependent"""
        if self._painter is not None:
            self._painter.restore()
            self._painter.restore()
            self._painter.end()
        
        self._paintdevice = canvas
        self._painter = QPainter(canvas)
        self._painter.setRenderHint(QPainter.Antialiasing)

        # invert the y axis
        self._painter.scale(1,-1)
        self._painter.translate(0,-canvas.height())

        Renderer.set_canvas(self,canvas)

    def _get_canvas_size(self,pd):
        """Get the canvas size tuple (width,height)"""
        return (pd.width(), pd.height())

    def push_state(self):
        """Store the current state on the stack.
        Current state includes default pose, pen and brush"""
        ### FIXME store things
        self._painter.save()

    def pop_state(self):
        """Restore the last saved state from the stack
        The state includes default pose, pen and brush"""
        ### FIXME store things
        self._painter.restore()

    def _calculate_bounds(self):
        transform = self._painter.worldTransform().inverted()[0]
        xs,ys = zip(
                    transform.map(0.0,0.0),
                    transform.map(0.0,float(self.size[1])),
                    transform.map(float(self.size[0]),float(self.size[1])),
                    transform.map(float(self.size[0]),0.0)
                    )

        self._bounds = (min(xs), min(ys), max(xs), max(ys))

    def _draw_grid(self):
        self.reset_pose()
        self._painter.setPen(self._grid_pen)
        xmin, ymin, xmax, ymax = self._bounds

        # Determine min/max x & y line indices:
        x_ticks = (int(xmin//self._grid_spacing), int(xmax//self._grid_spacing + 1))
        y_ticks = (int(ymin//self._grid_spacing), int(ymax//self._grid_spacing + 1))

        self._painter.drawLines(
            [QLineF(xmin, i * self._grid_spacing,
                    xmax, i * self._grid_spacing)
                for i in range(*y_ticks)])
        self._painter.drawLines(
            [QLineF(i * self._grid_spacing, ymin,
                    i * self._grid_spacing, ymax)
                for i in range(*x_ticks)])

    def scale(self, factor):
        """Scale drawing operations by factor
        To be implemented in subclasses."""
        self._painter.scale(factor,factor)

    def rotate(self, angle):
        """Rotate canvas by angle (in radians)
        To be implemented in subclasses."""
        self._painter.rotate(degrees(angle))

    def translate(self, dx, dy):
        """Translate canvas by dx, dy
        To be implemented in subclasses."""
        self._painter.translate(dx,dy)

    def clear_screen(self):
        """Erases the current screen with a white brush"""
        self._painter.save()
        self._painter.resetTransform()
        self.set_pen(0xFFFFFF)
        self.set_brush(0xFFFFFF)
        self.draw_rectangle(0,0,self.size[0],self.size[1])
        self._painter.restore()
        Renderer.clear_screen(self)

    @staticmethod
    def __qcolor(color):
        """Returns qcolor for a given ARGB color"""
        c = QColor(color)
        if color > 0xFFFFFF:
            c.setAlpha((color >> 24) & 0xFF)
        return c

    def set_pen(self,color=0, thickness=0):
        """Sets the line color and thickness.
        Color is interpreted as 0xAARRGGBB."""
        if color is None:
            self._painter.setPen(Qt.NoPen)
        else:
            self._painter.setPen(QPen(self.__qcolor(color),thickness))

    def set_brush(self,color):
        """Sets the fill color.
        Color is interpreted as 0xAARRGGBB."""
        if color is None:
            self._painter.setBrush(Qt.NoBrush)
        else:
            self._painter.setBrush(self.__qcolor(color))

    def draw_polygon(self,points):
        """Draws a polygon.
        Expects a list of points as a list of tuples or as a numpy array."""
        self._painter.drawPolygon(QPolygonF([QPointF(*point[:2]) for point in points]))

    def draw_ellipse(self, cx, cy, ra, rb = None):
        """Draws an ellipse."""
        if rb is None:
            rb = ra
        self._painter.drawEllipse(QRectF(cx-ra,cy-ra,2*ra,2*rb))

    def draw_rectangle(self, x, y, w, h):
        """Draws a rectangle."""
        self._painter.drawRect(QRectF(x,y,w,h))

    def draw_text(self, text, x, y, bgcolor = 0):
        """Draws a text string at the defined position."""
        pass

    def draw_line(self, x1, y1, x2, y2):
        """Draws a line using the current pen from (x1,y1) to (x2,y2)"""
        self._painter.drawLine(QLineF(x1,y1,x2,y2))
        
    def draw_point(self,x,y):
        """Draw a single point using the current pen at (x,y)"""
        self._painter.drawPoint(QPointF(x,y))
        
    def draw_points(self,points):
        """Draw a set of points, given as [(x,y)], using the current pen"""
        self._painter.drawPoints(QPolygonF([QPointF(x,y) for x,y in points]))
示例#20
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.TextAntialiasing)
        R = 100
        Pi = 3.14159
        deg = Pi * 72 / 180
        points = [
            QPoint(R, 0),
            QPoint(R * math.cos(deg), -R * math.sin(deg)),
            QPoint(R * math.cos(2 * deg), -R * math.sin(2 * deg)),
            QPoint(R * math.cos(3 * deg), -R * math.sin(3 * deg)),
            QPoint(R * math.cos(4 * deg), -R * math.sin(4 * deg))
        ]
        font = painter.font()
        font.setPointSize(12)
        font.setBold(False)
        painter.setFont(font)

        pen = QPen()
        pen.setWidth(2)
        pen.setColor(Qt.blue)
        pen.setStyle(Qt.SolidLine)
        pen.setCapStyle(Qt.FlatCap)
        pen.setJoinStyle(Qt.BevelJoin)
        painter.setPen(pen)

        brush = QBrush()
        brush.setColor(Qt.yellow)
        brush.setStyle(Qt.SolidPattern)
        painter.setBrush(brush)

        starPath = QPainterPath()
        starPath.moveTo(points[0])
        starPath.lineTo(points[2])
        starPath.lineTo(points[4])
        starPath.lineTo(points[1])
        starPath.lineTo(points[3])
        starPath.closeSubpath()

        starPath.addText(points[0], font, "0")
        starPath.addText(points[1], font, "1")
        starPath.addText(points[2], font, "2")
        starPath.addText(points[3], font, "3")
        starPath.addText(points[4], font, "4")

        painter.save()
        painter.translate(100, 120)
        painter.drawPath(starPath)
        painter.drawText(0, 0, "S1")
        painter.restore()

        painter.translate(300, 120)
        painter.scale(0.8, 0.8)
        painter.rotate(90)
        painter.drawPath(starPath)
        painter.drawText(0, 0, "S2")

        painter.resetTransform()
        painter.translate(500, 120)
        painter.rotate(-145)
        painter.drawPath(starPath)
        painter.drawText(0, 0, "S3")
示例#21
0
    def paintEvent(self, event: QPaintEvent):
        _start = perf_counter()
        num = self.num_tabs
        selected = self.selected
        arrow_width = self._arrow_width
        height = self.height()
        width = self._button_width
        first_width = self._first_button_width
        button = self._button_path
        button_box = QRect(0, 0, width + arrow_width, height)
        first_box = QRect(0, 0, first_width + arrow_width, height)
        icon_area = QRect(arrow_width + 10, 0, max(48, width / 2), height)
        text_box = QRect(arrow_width, 0, width - arrow_width, height)
        text_flags = Qt.AlignCenter | Qt.AlignVCenter
        states = self.states

        painter = QPainter(self)
        region = event.region()
        painter.setClipRegion(region)
        #torender = self._tabs_within(event.region())
        #print("regions:")
        #for rect in event.region().rects():
        #    print(" -  ", rect)
        #painter.setPen(Qt.NoPen)
        painter.setPen(
            QPen(Qt.black, 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        titleFont = painter.font()
        titleFont.setPointSizeF(14)
        titleFont.setBold(True)
        painter.setFont(titleFont)

        painter.translate(num * width + first_width, 0)

        if region.intersects(painter.transform().mapRect(button_box)):
            painter.setBrush(states[num].get_color(num == selected))
            painter.drawPath(self._last_button_path)

        for i in reversed(range(num)):
            painter.translate(-width, 0)
            if not region.intersects(painter.transform().mapRect(button_box)):
                continue

            painter.setBrush(states[i].get_color(i == selected))
            painter.drawPath(button)

            if states[i].state == State.ACTIVE:
                painter.save()
                painter.setPen(Qt.NoPen)
                gw = (width + self._arrow_width) * 2
                gradient = QLinearGradient(0, 0, gw, 0)
                value = self._working_anim.value
                gradient.setColorAt(max(0.0, value - 0.2),
                                    QColor(255, 255, 255, 0))
                gradient.setColorAt(value, QColor(255, 255, 255, 180))
                gradient.setColorAt(min(1.0, value + 0.2),
                                    QColor(255, 255, 255, 0))
                brush = QBrush(gradient)
                brush.setTransform(brush.transform().translate(-gw / 4, 0))
                gradient_height = int(height * 0.2)
                painter.setBrush(brush)
                #painter.setClipRect(0, 0, width+self._arrow_width, gradient_height)
                #painter.drawPath(button)
                #painter.setClipRect(0, height-gradient_height, width+self._arrow_width, gradient_height)
                painter.drawPath(button)
                self._active_box = painter.transform().mapRect(button_box)
                painter.restore()

            #if states[i].icon:
            #    states[i].icon.paint(painter, icon_area)

            text = states[i].text
            if text:
                _, _, short = text.rpartition('-')
                painter.drawText(text_box, text_flags, short.capitalize())

        if region.intersects(first_box):
            painter.resetTransform()
            painter.setBrush(State.UNKNOWN.get_color(-1 == selected))
            painter.drawPath(self._first_button_path)

            if self.is_running:
                icon = self.style().standardIcon(QStyle.SP_MediaStop)
            else:
                icon = self.style().standardIcon(QStyle.SP_MediaPlay)

            size = min(self._first_button_width, self.height()) * 0.8
            painter.translate(5, (self.height() - size) / 2)
            icon.paint(painter, QRect(0, 0, size, size))

        _end = perf_counter()
        if not self._paint_times:
            self._paint_times = times = []
        else:
            times = self._paint_times
        times.append(_end - _start)
        if len(times) > 60:
            avg = sum(times) / len(times) * 1000000
            print("Average render time %.2fns" % (avg, ))
            self._paint_times = None