Exemple #1
0
 def paintEvent(self, event):
     _size = self.size() - QSize(2, 2)
     if (_size.isEmpty()):
         return
     origX = (_size.width() - self.mNewSize.width() * self.mScale) / 2 + 0.5
     origY = (_size.height() -
              self.mNewSize.height() * self.mScale) / 2 + 0.5
     oldRect = QRect(self.mOffset, self.mOldSize)
     painter = QPainter(self)
     painter.translate(origX, origY)
     painter.scale(self.mScale, self.mScale)
     pen = QPen(Qt.black)
     pen.setCosmetic(True)
     painter.setPen(pen)
     painter.drawRect(QRect(QPoint(0, 0), self.mNewSize))
     pen.setColor(Qt.white)
     painter.setPen(pen)
     painter.setBrush(Qt.white)
     painter.setOpacity(0.5)
     painter.drawRect(oldRect)
     pen.setColor(Qt.black)
     pen.setStyle(Qt.DashLine)
     painter.setOpacity(1.0)
     painter.setBrush(Qt.NoBrush)
     painter.setPen(pen)
     painter.drawRect(oldRect)
     painter.end()
Exemple #2
0
    def paint(self,
              painter: QtGui.QPainter,
              option: 'QStyleOptionGraphicsItem',
              widget: typing.Optional[QWidget] = ...):
        painter.save()
        scale = 1 / self.downsample
        painter.scale(scale, scale)

        # for grid_rect, color in zip(self.grid_rects_0_level, self.color_alphas):
        #     painter.setBrush(color)
        #     painter.drawRect(*grid_rect)

        for color_alpha, rects in self.color_alpha__rects_0_level.items():
            color = QColor(*self.base_color_rgb, color_alpha)
            painter.setBrush(color)
            qrectfs = self.star_map_(QRectF, rects)
            painter.drawRects(qrectfs)

        # for color_alpha, rects in enumerate(self.color_alpha__rects_0_level):
        #     if rects:
        #         color = QColor(*self.base_color_rgb, color_alpha)
        #         painter.setBrush(color)
        #         qrectfs = self.star_map_(QRectF, rects)
        #         painter.drawRects(qrectfs)
        painter.restore()
Exemple #3
0
def save_pdf(widget, filename, preview=False):
    # Creation du printer
    printer = QPrinter()
    file_names = filename
    printer.setOutputFileName(file_names)
    printer.setOutputFormat(QPrinter.PdfFormat)
    printer.setPageMargins(10, 10, 10, 10, QPrinter.Point)

    # Calcul le ratio de redimensionnement
    page_width = printer.pageRect().width()
    page_height = printer.pageRect().height()
    widget_width = widget.width()
    widget_height = widget.height()
    ratio = min(page_width / widget_width, page_height / widget_height)

    # Calcul du positionnement
    pos_x = max(0, (page_width - ratio * widget_width) / 2)
    pos_y = max(0, (page_height - ratio * widget_height) / 2)

    # Render le widget dans une image QPicture pour stocker
    # les directives de dessin
    picture = QPicture()
    widget_painter = QPainter(picture)
    widget_painter.scale(ratio, ratio)
    widget.render(widget_painter)
    widget_painter.end()

    # Render la QPicture en utilisant le QPrinter
    picture_painter = QPainter()
    picture_painter.begin(printer)
    picture_painter.drawPicture(QPointF(pos_x, pos_y), picture)
    picture_painter.end()

    if preview:
        affiche_pdf(file_names)
Exemple #4
0
    def _draw_video_band(self, painter: QPainter) -> None:
        try:
            current_stream = self._api.video.current_stream
            pixels = self._pixels.transpose(1, 0, 2)

            min_pts = self.pts_from_x(0)
            max_pts = self.pts_from_x(self.width() - 1)

            pts_range = np.linspace(min_pts, max_pts, self.width())
            frame_idx_range = current_stream.frame_idx_from_pts(pts_range)

            cache = self._worker.cache.get(current_stream.uid)
            if cache is not None:
                for x, frame_idx in enumerate(frame_idx_range):
                    pixels[x] = cache[frame_idx]

            # pylint: disable=unsubscriptable-object
            image = QImage(
                self._pixels.data,
                self._pixels.shape[1],
                self._pixels.shape[0],
                self._pixels.strides[0],
                QImage.Format_RGB888,
            )
            # pylint: enable=unsubscriptable-object

            painter.save()
            painter.scale(1,
                          painter.viewport().height() / (BAND_RESOLUTION - 1))
            painter.drawPixmap(0, 0, QPixmap.fromImage(image))
            painter.restore()
        except ResourceUnavailable:
            return
Exemple #5
0
    def paintEvent(self, event):
        painter = QPainter(self)

        image = self._alignment.image()
        painter.drawImage(self.rect(), QImage(image.tobytes(), *image.shape,
                                              QImage.Format_Grayscale8))

        painter.setCompositionMode(QPainter.CompositionMode_Lighten)
        pen = QPen()
        pen.setWidth(self.width()/500)
        pen.setCapStyle(Qt.RoundCap)

        painter.scale(self.width() / image.shape[0],
                      self.height() / image.shape[1])

        def drawCentre(color, y, x):
            pen.setColor(color)
            painter.setPen(pen)
            length = self.width() /10
            painter.translate(x, y)
            painter.drawLine(-length, -length, length, length)
            painter.drawLine(-length, length, length, -length)
            painter.drawEllipse(QPoint(0, 0), length/2, length/2)
            painter.translate(-x, -y)

        drawCentre(Qt.red, *self._alignment.reference())
        drawCentre(Qt.green, *self._alignment.current())
    def paintEvent(self, evt):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)

        # 画边框
        painter.setPen(Qt.white)
        painter.drawRect(self.rect())

        realSize = min(self.width(), self.height()) - 10
        painter.translate(self.width() / 2.0, self.height() / 2.0)
        painter.scale(realSize / 1000.0, realSize / 1000.0)
        painter.rotate(self.rotateAngle)

        # 画外圈
        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(80, 80, 80))
        painter.drawEllipse(QPointF(0, 0), 500, 500)

        # 园内部四个扇形区域,蓝白交叉
        startAngle = 0
        spanAngle = 90 * 16
        pieRect = QRectF(QPointF(-400, -400), QPointF(400, 400))
        for i in range(4):
            color = QColor(0, 120, 200) if i % 2 else QColor(240, 240, 240)
            painter.setBrush(color)
            painter.drawPie(pieRect, startAngle, spanAngle)
            startAngle += spanAngle
Exemple #7
0
    def draw_tiles(self, layer_data, painter: QtGui.QPainter, global_transform):
        tiles = self.dm.tiles.only_tiles()
        for i in range(len(tiles)):
            for j in range(len(tiles[0])):
                tile = tiles[i][j]
                orientation = tile.orientation
                painter.scale(self.sc, self.sc)
                painter.translate(tile.i * self.map.gridSize, (len(tiles[0]) - 1 - tile.j) * self.map.gridSize)

                my_transform = QTransform()
                my_transform.rotate(get_degree_for_orientation(orientation))
                img = self.tileSprites[tile.type].transformed(my_transform)
                painter.drawImage(QtCore.QRectF(0, 0, self.map.gridSize, self.map.gridSize),
                                  img)
                # print(self.tileSelection)
                if self.is_selected_tile(tile):
                    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))
                if tile.j == 0 and tile.i == 0:
                    painter.setPen(QtGui.QColor('blue'))
                    painter.drawRect(QtCore.QRectF(1, 1, self.map.gridSize - 1, self.map.gridSize - 1))
                painter.setTransform(global_transform, False)
    def paintEvent(self, event):
        rect = event.rect()
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        painter.fillRect(rect, self._backgroundColor)
        if not self._glyphs:
            return

        painter.translate(0, self.height())
        painter.scale(1, -1)

        availableHeight = self.height() - 2 * self._buffer
        availableWidth = self.width() - 2 * self._buffer
        scale = availableHeight / (self._upm * 1.2)
        yOffset = abs(self._descender * scale) + self._buffer
        scale = min(scale, availableWidth / self._maxWidth)

        for glyph in self._glyphs:
            if self._alignment == "left":
                xOffset = self._buffer
            elif self._alignment == "center":
                xOffset = (self.width() - (glyph.width * scale)) / 2
            else:
                xOffset = availableWidth + self._buffer - glyph.width * scale
            path = glyph.getRepresentation("defconQt.QPainterPath")
            painter.save()
            painter.translate(xOffset, yOffset)
            painter.scale(scale, scale)
            painter.fillPath(path, self._glyphColor)
            painter.restore()
    def paintEvent(self, event):
        """Paints the board."""
        painter = QPainter(self)

        painter.setRenderHint(QPainter.Antialiasing, True)

        painter.setPen(QPen(Qt.black, Qt.SolidLine))
        painter.setBrush(QBrush(Qt.white, Qt.SolidPattern))

        painter.setClipRect(0, 0, self.canvas.width(), self.canvas.height())

        # background
        painter.drawRect(0, 0, self.canvas.width(), self.canvas.height())

        painter.translate(*self.translation)
        painter.scale(self.scale, self.scale)

        # draw vertexes
        for n1 in self.graph.get_nodes():
            for n2, weight in n1.get_neighbours().items():
                self.draw_vertex(n1, n2, weight, painter)

        # draw nodes
        for node in self.graph.get_nodes():
            self.draw_node(node, painter)
 def paintEvent(self, event):
     painter = QPainter()
     painter.begin(self)
     painter.scale(6, 6)
     # Use antialiasing to smooth curved edges
     painter.setRenderHint(QPainter.Antialiasing)
     self.drawRectangles(painter)
Exemple #11
0
    def paintEvent(self, event):
        rect = QRect(10, 20, 80, 60)

        path = QPainterPath()
        path.moveTo(20, 80)
        path.lineTo(20, 30)
        path.cubicTo(80, 0, 50, 50, 80, 80)

        startAngle = 30 * 16
        arcLength = 120 * 16

        painter = QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        if self.antialiased:
            painter.setRenderHint(QPainter.Antialiasing)

        for x in range(0, self.width(), 100):
            for y in range(0, self.height(), 100):
                painter.save()
                painter.translate(x, y)
                if self.transformed:
                    painter.translate(50, 50)
                    painter.rotate(60.0)
                    painter.scale(0.6, 0.9)
                    painter.translate(-50, -50)

                if self.shape == RenderArea.Line:
                    painter.drawLine(rect.bottomLeft(), rect.topRight())
                elif self.shape == RenderArea.Points:
                    painter.drawPoints(RenderArea.points)
                elif self.shape == RenderArea.Polyline:
                    painter.drawPolyline(RenderArea.points)
                elif self.shape == RenderArea.Polygon:
                    painter.drawPolygon(RenderArea.points)
                elif self.shape == RenderArea.Rect:
                    painter.drawRect(rect)
                elif self.shape == RenderArea.RoundedRect:
                    painter.drawRoundedRect(rect, 25, 25, Qt.RelativeSize)
                elif self.shape == RenderArea.Ellipse:
                    painter.drawEllipse(rect)
                elif self.shape == RenderArea.Arc:
                    painter.drawArc(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Chord:
                    painter.drawChord(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Pie:
                    painter.drawPie(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Path:
                    painter.drawPath(path)
                elif self.shape == RenderArea.Text:
                    painter.drawText(rect, Qt.AlignCenter,
                            "PyQt by\nRiverbank Computing")
                elif self.shape == RenderArea.Pixmap:
                    painter.drawPixmap(10, 10, self.pixmap)

                painter.restore()

        painter.setPen(self.palette().dark().color())
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
Exemple #12
0
    def paintEvent(self, event):
        # TODO: maybe use self.upm*(1+2*BufferHeight) for the denominator as in
        # fontView
        scale = self.height() / (self.upm * 1.2)
        x_offset = \
            (self.width() - self.maxWidth * scale - self.padding * 2) / 2
        if x_offset < 0:
            scale *= 1 + 2 * x_offset / (self.maxWidth * scale)
            x_offset = 0
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.padding, self.padding +
                          (self.ascender * 1.2) * scale)
        painter.scale(scale, -scale)

        col = QColor(Qt.black)
        col.setAlphaF(.2)
        for glyph in self.glyphs:
            if self.alignRight:
                dist = self.maxWidth - glyph.width
            else:
                dist = 0
            glyphPath = glyph.getRepresentation("defconQt.QPainterPath")
            painter.save()
            painter.translate(x_offset + dist, 0)
            painter.fillPath(glyphPath, col)
            painter.restore()
Exemple #13
0
    def impression(self):
        # Creation du printer
        printer = QPrinter()
        dialog = QPrintDialog(printer, self)
        if dialog.exec_() != QDialog.Accepted:
            return
        printer.setPageMargins(10, 10, 10, 10, QPrinter.Point)

        # Calcul le ratio de redimensionnement
        page_width = printer.pageRect().width()
        page_height = printer.pageRect().height()
        widget_width = self.rapport.width()
        widget_height = self.rapport.height()
        ratio = min(page_width / widget_width, page_height / widget_height)

        # Calcul du positionnement
        pos_x = max(0, (page_width - ratio * widget_width) / 2)
        pos_y = max(0, (page_height - ratio * widget_height) / 2)

        # Render le widget dans une image QPicture pour stocker
        # les directives de dessin
        picture = QPicture()
        widget_painter = QPainter(picture)
        widget_painter.scale(ratio, ratio)
        self.rapport.render(widget_painter)
        widget_painter.end()

        # Render la QPicture en utilisant le QPrinter
        picture_painter = QPainter()
        picture_painter.begin(printer)
        picture_painter.drawPicture(QPointF(pos_x, pos_y), picture)
        picture_painter.end()
Exemple #14
0
def print_widget_as_pdf(wid,pdfname):
	# Print options
	if not pdfname: pdfname = "test"
	if wid is None:
		print("No widget")
		return
	printer = QPrinter(QPrinter.HighResolution)
	printer.setOrientation(QPrinter.Landscape)
	printer.setPaperSize(QPrinter.A9)
	printer.setPageSize(QPrinter.A9)
	printer.setPageMargins(5, 5, 5, 5, QPrinter.Millimeter)
	# Setting the margins and then calling setFullPage() will discard the margins.
	printer.setFullPage(True)
	printer.setOutputFormat(QPrinter.PdfFormat)
	print(pdfname)
	printer.setOutputFileName(pdfname+".pdf")

	# Render/Paint it
	painter = QPainter()
	painter.begin(printer)

	# Establish scaling transform
	scaleX = printer.pageRect().width() / wid.rect().width()
	scaleY = printer.pageRect().height() / wid.rect().height()
	useScale = min(scaleX, scaleY)
	painter.scale(useScale, useScale)

	wid.render(painter)
	painter.end()
Exemple #15
0
    def btn3clicked(self):
        # 프린터 생성, 실행
        printer = QPrinter()
        dlg = QPrintDialog(printer, self)
        if dlg.exec() == QDialog.Accepted:
            # Painter 생성
            qp = QPainter()
            qp.begin(printer)

            # 여백 비율
            wgap = printer.pageRect().width() * 0.1
            hgap = printer.pageRect().height() * 0.1

            # 화면 중앙에 위젯 배치
            xscale = (printer.pageRect().width() - wgap) / self.table.width()
            yscale = (printer.pageRect().height() - hgap) / self.table.height()
            scale = xscale if xscale < yscale else yscale
            qp.translate(
                printer.paperRect().x() + printer.pageRect().width() / 2,
                printer.paperRect().y() + printer.pageRect().height() / 2)
            qp.scale(scale, scale)
            qp.translate(-self.table.width() / 2, -self.table.height() / 2)

            # 인쇄
            self.table.render(qp)

            qp.end()
Exemple #16
0
 def paintEvent(self, event):
     _size = self.size() - QSize(2, 2)
     if (_size.isEmpty()):
         return
     origX = (_size.width() - self.mNewSize.width() * self.mScale) / 2 + 0.5
     origY = (_size.height() - self.mNewSize.height() * self.mScale) / 2 + 0.5
     oldRect = QRect(self.mOffset, self.mOldSize)
     painter = QPainter(self)
     painter.translate(origX, origY)
     painter.scale(self.mScale, self.mScale)
     pen = QPen(Qt.black)
     pen.setCosmetic(True)
     painter.setPen(pen)
     painter.drawRect(QRect(QPoint(0, 0), self.mNewSize))
     pen.setColor(Qt.white)
     painter.setPen(pen)
     painter.setBrush(Qt.white)
     painter.setOpacity(0.5)
     painter.drawRect(oldRect)
     pen.setColor(Qt.black)
     pen.setStyle(Qt.DashLine)
     painter.setOpacity(1.0)
     painter.setBrush(Qt.NoBrush)
     painter.setPen(pen)
     painter.drawRect(oldRect)
     painter.end()
Exemple #17
0
    def createImage(self, transform):
        scaledRect = transform.mapRect(QRect(0, 0, 25, 25))
        image = QImage(scaledRect.width(), scaledRect.height(),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(0)
        painter = QPainter(image)
        painter.scale(transform.m11(), transform.m22())
        painter.setRenderHints(QPainter.TextAntialiasing | QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
        painter.setPen(Qt.NoPen)

        if Colors.useEightBitPalette:
            painter.setBrush(QColor(102, 175, 54))
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QColor(255, 255, 255))
            painter.drawText(10, 15, self.letter)
        else:
            brush = QLinearGradient(0, 0, 0, 25)
            brush.setSpread(QLinearGradient.PadSpread)
            brush.setColorAt(0.0, QColor(102, 175, 54, 200))
            brush.setColorAt(1.0, QColor(102, 175, 54, 60))
            painter.setBrush(brush)
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QColor(255, 255, 255, 255))
            painter.drawText(10, 15, self.letter)

        return image
Exemple #18
0
    def createImage(self, transform):
        scaledRect = transform.mapRect(QRect(0, 0, 25, 25))
        image = QImage(scaledRect.width(), scaledRect.height(),
                       QImage.Format_ARGB32_Premultiplied)
        image.fill(0)
        painter = QPainter(image)
        painter.scale(transform.m11(), transform.m22())
        painter.setRenderHints(QPainter.TextAntialiasing
                               | QPainter.Antialiasing
                               | QPainter.SmoothPixmapTransform)
        painter.setPen(Qt.NoPen)

        if Colors.useEightBitPalette:
            painter.setBrush(QColor(102, 175, 54))
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QColor(255, 255, 255))
            painter.drawText(10, 15, self.letter)
        else:
            brush = QLinearGradient(0, 0, 0, 25)
            brush.setSpread(QLinearGradient.PadSpread)
            brush.setColorAt(0.0, QColor(102, 175, 54, 200))
            brush.setColorAt(1.0, QColor(102, 175, 54, 60))
            painter.setBrush(brush)
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QColor(255, 255, 255, 255))
            painter.drawText(10, 15, self.letter)

        return image
Exemple #19
0
    def paintEvent(self, event):
        global real_time, minotaur_standard_time

        actual_time_updater()

        side = min(self.width(), self.height())

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogClock.hourColor)

        painter.save()
        hour_adjust = 30.0 * (
            (int(real_time.hour) + int(real_time.minute) / 60.0))
        hour = math.floor(hour_adjust / 30.0)
        painter.rotate(hour_adjust)
        painter.drawConvexPolygon(AnalogClock.hourHand)
        painter.restore()

        painter.setPen(AnalogClock.hourColor)

        for i in range(12):
            painter.drawLine(88, 0, 96, 0)
            painter.rotate(30.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogClock.minuteColor)

        painter.save()
        minute_adjust = 6.0 * (
            (int(real_time.minute) + int(real_time.second) / 60.0))
        if minute_adjust < 0:
            minute_adjust += 360
        minute = math.floor(minute_adjust / 6.0)
        painter.rotate(minute_adjust)
        painter.drawConvexPolygon(AnalogClock.minuteHand)
        painter.restore()

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogClock.secondColor)

        painter.save()
        second_adjust = 6.0 * int(real_time.second)
        if second_adjust < 0:
            second_adjust += 360
        second = math.floor(second_adjust / 6.0)
        painter.rotate(second_adjust)
        painter.drawConvexPolygon(AnalogClock.secondHand)
        painter.restore()

        painter.setPen(AnalogClock.minuteColor)

        for j in range(60):
            if (j % 5) != 0:
                painter.drawLine(92, 0, 96, 0)
            painter.rotate(6.0)
Exemple #20
0
    def paintEvent(self, event):
        # TODO: maybe use self.upm*(1+2*BufferHeight) for the denominator as in
        # fontView
        scale = self.height() / (self.upm * 1.2)
        x_offset = \
            (self.width() - self.maxWidth * scale - self.padding * 2) / 2
        if x_offset < 0:
            scale *= 1 + 2 * x_offset / (self.maxWidth * scale)
            x_offset = 0
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.padding,
                          self.padding + (self.ascender * 1.2) * scale)
        painter.scale(scale, -scale)

        col = QColor(Qt.black)
        col.setAlphaF(.2)
        for glyph in self.glyphs:
            if self.alignRight:
                dist = self.maxWidth - glyph.width
            else:
                dist = 0
            glyphPath = glyph.getRepresentation("defconQt.QPainterPath")
            painter.save()
            painter.translate(x_offset + dist, 0)
            painter.fillPath(glyphPath, col)
            painter.restore()
Exemple #21
0
    def createImage(self, transform):
        if self.type == DemoTextItem.DYNAMIC_TEXT:
            return None

        sx = min(transform.m11(), transform.m22())
        sy = max(transform.m22(), sx)

        textItem = QGraphicsTextItem()
        textItem.setHtml(self.text)
        textItem.setTextWidth(self.textWidth)
        textItem.setFont(self.font)
        textItem.setDefaultTextColor(self.textColor)
        textItem.document().setDocumentMargin(2)

        w = textItem.boundingRect().width()
        h = textItem.boundingRect().height()
        image = QImage(int(w * sx), int(h * sy),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(QColor(0, 0, 0, 0).rgba())
        painter = QPainter(image)
        painter.scale(sx, sy)
        style = QStyleOptionGraphicsItem()
        textItem.paint(painter, style, None)

        return image
Exemple #22
0
    def export_pdf(self, widget: QDialog):
        # Get user-specified file path
        file_path, _ = QFileDialog.getSaveFileName(widget, "Export Egram Report",
                                                   f"egram_report_{self._report_gen_time}.pdf",
                                                   "PDF files (.pdf);;All Files ()")

        # If the user specified a file path
        if file_path:
            # Add .pdf suffix if it doesn't exist
            if QFileInfo(file_path).suffix() == "":
                file_path += ".pdf"

            # Set up printer and painter to create pdf file
            printer = QPrinter(QPrinter.ScreenResolution)
            printer.setOrientation(QPrinter.Landscape)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(file_path)
            printer.setPageMargins(0, 0, 0, 0, QPrinter.Point)
            painter = QPainter(printer)

            # Scale widget
            x_scale = printer.pageRect().width() * 1.0 / widget.width()
            y_scale = printer.pageRect().height() * 1.0 / widget.height()
            scale = min(x_scale, y_scale)
            painter.translate(printer.paperRect().center())
            painter.scale(scale, scale)
            painter.translate(-widget.width() / 2, -widget.height() / 2)

            # Dump the contents of the egram report widget to the pdf, and write it to disk
            widget.render(painter)
            painter.end()
Exemple #23
0
    def paintEvent(self, event=None):
        side = min(self.width(), self.height())
        pos = self.value
        ref_pos = self.refValue

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2 + 10, self.height() / 2)
        painter.scale(side / 230.0, side / 230.0)

        painter.setBrush(Qt.NoBrush)
        painter.setPen(QColor(0, 0, 0))

        painter.drawRect(-100, -100, 2 * 100, 2 * 100)

        for i in range(20):
            x = -100 + i * 10
            painter.drawLine(x, 100, x, 98)
            painter.drawLine(x, -100, x, -98)
            painter.drawLine(-100, x, -98, x)
            painter.drawLine(100, x, 98, x)

        painter.drawLine(-100, 0, 100, 0)
        painter.drawLine(-100, 50, 100, 50)
        painter.drawLine(-100, -50, 100, -50)
        painter.drawLine(-50, -100, -50, 100)
        painter.drawLine(50, 100, 50, -100)
        painter.drawLine(0, -100, 0, 100)

        painter.setBrush(self.ref_color)
        painter.setPen(self.ref_color)
        painter.drawEllipse(
            (ref_pos[0] * (100 / self.range_x)) - self.pointWidth,
            (ref_pos[1] * -(100 / self.range_y)) - self.pointWidth,
            2.1 * self.pointWidth, 2.1 * self.pointWidth)

        painter.setBrush(self.color)
        painter.drawEllipse((pos[0] * (100 / self.range_x)) - self.pointWidth,
                            (pos[1] * -(100 / self.range_y)) - self.pointWidth,
                            2 * self.pointWidth, 2 * self.pointWidth)

        #        painter.save()
        #        painter.setPen(QColor(0,0,0))
        #        painter.rotate(180)
        #        for i in range(2):
        #            painter.drawLine(-1*((pos[0] * (100/self.scale)) - self.pointWidth/2), -1*((pos[1] * -(100/self.scale)) - self.pointWidth/2),
        #            -1*((pos[0] * (100/self.scale)) + self.pointWidth/2), -1*((pos[1] * -(100/self.scale)) + self.pointWidth/2))
        #            painter.rotate(180)
        #        painter.restore()

        painter.setPen(QColor(0, 0, 0))
        font = painter.font()
        font.setPointSize(font.pointSize() * 1.2)
        painter.setFont(font)

        painter.drawText(QRectF(-107, 102, 30, 20), str(self.scale_x[0]))
        painter.drawText(QRectF(90, 102, 30, 20), str(1 * self.scale_x[1]))

        painter.drawText(QRectF(-130, 90, 30, 20), str(self.scale_y[0]))
        painter.drawText(QRectF(-125, -105, 30, 20), str(1 * self.scale_y[1]))
Exemple #24
0
    def paintEvent(self, event):
        rect = QRect(10, 20, 80, 60)

        path = QPainterPath()
        path.moveTo(20, 80)
        path.lineTo(20, 30)
        path.cubicTo(80, 0, 50, 50, 80, 80)

        startAngle = 30 * 16
        arcLength = 120 * 16

        painter = QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        if self.antialiased:
            painter.setRenderHint(QPainter.Antialiasing)

        for x in range(0, self.width(), 100):
            for y in range(0, self.height(), 100):
                painter.save()
                painter.translate(x, y)
                if self.transformed:
                    painter.translate(50, 50)
                    painter.rotate(60.0)
                    painter.scale(0.6, 0.9)
                    painter.translate(-50, -50)

                if self.shape == RenderArea.Line:
                    painter.drawLine(rect.bottomLeft(), rect.topRight())
                elif self.shape == RenderArea.Points:
                    painter.drawPoints(RenderArea.points)
                elif self.shape == RenderArea.Polyline:
                    painter.drawPolyline(RenderArea.points)
                elif self.shape == RenderArea.Polygon:
                    painter.drawPolygon(RenderArea.points)
                elif self.shape == RenderArea.Rect:
                    painter.drawRect(rect)
                elif self.shape == RenderArea.RoundedRect:
                    painter.drawRoundedRect(rect, 25, 25, Qt.RelativeSize)
                elif self.shape == RenderArea.Ellipse:
                    painter.drawEllipse(rect)
                elif self.shape == RenderArea.Arc:
                    painter.drawArc(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Chord:
                    painter.drawChord(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Pie:
                    painter.drawPie(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Path:
                    painter.drawPath(path)
                elif self.shape == RenderArea.Text:
                    painter.drawText(rect, Qt.AlignCenter,
                                     "PyQt by\nRiverbank Computing")
                elif self.shape == RenderArea.Pixmap:
                    painter.drawPixmap(10, 10, self.pixmap)

                painter.restore()

        painter.setPen(self.palette().dark().color())
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
    def paintEvent(self, evt):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setPen(QPen(Qt.black, 1))

        realSize = min(self.width(), self.height())  # 窗口的短边
        painter.translate(self.width() / 2.0, self.height() / 2.0)  # 原点平移到窗口中心
        painter.scale(realSize / self.scaledSize, realSize / self.scaledSize)  # 缩放,窗口的短边值映射为self.scaledSize
        gradient = QRadialGradient(QPointF(0, 0), self.scaledSize / 2.0, QPointF(0, 0))  # 辐射渐变

        # 画边框外圈和内圈
        for color, radius in [(self.colorBorderOut, self.radiusBorderOut),  # 边框外圈
                              (self.colorBorderIn, self.radiusBorderIn)]:  # 边框内圈
            gradient.setColorAt(1, color)
            painter.setBrush(QBrush(gradient))
            painter.drawEllipse(QPointF(0, 0), radius, radius)

        # 画内圆
        if self.state == 'off':
            gradient.setColorAt(0, self.colorOffBegin)
            gradient.setColorAt(1, self.colorOffEnd)
        else:
            gradient.setColorAt(0, self.colorOnBegin)
            gradient.setColorAt(1, self.colorOnEnd)

        painter.setBrush(QBrush(gradient))
        painter.drawEllipse(QPointF(0, 0), self.radiusCircle, self.radiusCircle)
Exemple #26
0
    def _draw_video_band(self, painter: QtGui.QPainter) -> None:
        current_stream = self._api.video.current_stream
        if not current_stream or not current_stream.timecodes:
            return

        pixels = self._pixels.transpose(1, 0, 2)

        min_pts = self.pts_from_x(0)
        max_pts = self.pts_from_x(self.width() - 1)

        pts_range = np.linspace(min_pts, max_pts, self.width())
        frame_idx_range = self._api.video.current_stream.frame_idx_from_pts(
            pts_range)

        cache = self._worker.cache.get(current_stream.uid)
        if cache is not None:
            for x, frame_idx in enumerate(frame_idx_range):
                pixels[x] = cache[frame_idx]

        image = QtGui.QImage(
            self._pixels.data,
            self._pixels.shape[1],
            self._pixels.shape[0],
            self._pixels.strides[0],
            QtGui.QImage.Format_RGB888,
        )
        painter.save()
        painter.scale(1, painter.viewport().height() / (BAND_RESOLUTION - 1))
        painter.drawPixmap(0, 0, QtGui.QPixmap.fromImage(image))
        painter.restore()
Exemple #27
0
    def paintEvent(self, event):
        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing, True)
        p.save()

        side = self.height()
        p.scale(side / 100.0, side / 100.0)
        width = 100 * self.width()
        height = 100 * self.height()

        width = 100.0 * self.width() / self.height()
        height = 100.0

        pen = QPen(p.pen())

        pen.setColor(QColor(32, 32, 32))
        pen.setWidthF(6.0)
        p.setPen(pen)
        p.setBrush(Qt.black)
        p.drawRoundedRect(3, 3, width - 6, height - 6, 7, (7 * width) / height)

        w = (width - 2 * self.Y_OFFSET) / self.m_digits
        x = (self.m_digits - 1) * w
        h = height - 2 * self.Y_OFFSET
        c = self.m_value
        r = 0

        for i in range(self.m_digits):
            r = c % 10
            c = c // 10
            rect = QRectF(x + self.X_OFFSET, self.Y_OFFSET, w, h)
            self.m_svg.render(p, "d{}".format(r), rect)
            x -= w

        p.restore()
Exemple #28
0
    def createImage(self, transform):
        if self.type == DemoTextItem.DYNAMIC_TEXT:
            return None

        sx = min(transform.m11(), transform.m22())
        sy = max(transform.m22(), sx)

        textItem = QGraphicsTextItem()
        textItem.setHtml(self.text)
        textItem.setTextWidth(self.textWidth)
        textItem.setFont(self.font)
        textItem.setDefaultTextColor(self.textColor)
        textItem.document().setDocumentMargin(2)

        w = textItem.boundingRect().width()
        h = textItem.boundingRect().height()
        image = QImage(int(w * sx), int(h * sy),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(QColor(0, 0, 0, 0).rgba())
        painter = QPainter(image)
        painter.scale(sx, sy)
        style = QStyleOptionGraphicsItem()
        textItem.paint(painter, style, None)

        return image
Exemple #29
0
    def createImage(self, transform):
        original = QImage(self.image)
        if original.isNull():
            return original

        size = transform.map(QPoint(self.maxWidth, self.maxHeight))
        w = size.x()
        h = size.y()

        # Optimization: if image is smaller than maximum allowed size, just
        # return the loaded image.
        if original.size().height() <= h and original.size().width() <= w and not self.adjustSize and self.scale == 1:
            return original

        # Calculate what the size of the final image will be.
        w = min(w, float(original.size().width()) * self.scale)
        h = min(h, float(original.size().height()) * self.scale)

        adjustx = 1.0
        adjusty = 1.0
        if self.adjustSize:
            adjustx = min(transform.m11(), transform.m22())
            adjusty = max(transform.m22(), adjustx)
            w *= adjustx
            h *= adjusty

        # Create a new image with correct size, and draw original on it.
        image = QImage(int(w + 2), int(h + 2),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(QColor(0, 0, 0, 0).rgba())
        painter = QPainter(image)
        painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
        if self.adjustSize:
            painter.scale(adjustx, adjusty)
        if self.scale != 1:
            painter.scale(self.scale, self.scale)
        painter.drawImage(0, 0, original)

        if not self.adjustSize:
            # Blur out edges.
            blur = 30

            if h < original.height():
                brush1 = QLinearGradient(0, h - blur, 0, h)
                brush1.setSpread(QLinearGradient.PadSpread)
                brush1.setColorAt(0.0, QColor(0, 0, 0, 0))
                brush1.setColorAt(1.0, Colors.sceneBg1)
                painter.fillRect(0, int(h) - blur, original.width(), int(h),
                        brush1)

            if w < original.width():
                brush2 = QLinearGradient(w - blur, 0, w, 0)
                brush2.setSpread(QLinearGradient.PadSpread)
                brush2.setColorAt(0.0, QColor(0, 0, 0, 0))
                brush2.setColorAt(1.0, Colors.sceneBg1)
                painter.fillRect(int(w) - blur, 0, int(w), original.height(),
                        brush2)

        return image
Exemple #30
0
 def paintEvent(self, event: QPaintEvent):
     qp = QPainter()
     qp.begin(self)
     qp.scale(self.scale, self.scale)
     qp.translate(self.offset / self.scale)
     qp.setRenderHint(QPainter.Antialiasing)
     self.draw_nodes(qp)
     qp.end()
Exemple #31
0
    def save(self,
             path,
             filetype=None,
             title=None,
             description=None,
             svg_dpi=SVG_INKSCAPE):
        if path is None or not isinstance(path, str):
            logger.error('please provide a valide path to save the image "' +
                         str(path) + '"')
            return
        if filetype is None:
            if path.lower().endswith('.svg'):
                filetype = 'svg'
            else:
                filetype = 'raster'
        dpi = 72  # 300 # inkscape 96 ? check for illustrator --> check

        if filetype == 'svg':
            generator = QSvgGenerator()
            generator.setFileName(path)
            if svg_dpi == self.SVG_ILLUSTRATOR:
                generator.setSize(QSize(595, 842))
                generator.setViewBox(QRect(0, 0, 595, 842))
            else:
                generator.setSize(QSize(794, 1123))
                generator.setViewBox(QRect(0, 0, 794, 1123))

            if title is not None and isinstance(title, str):
                generator.setTitle(title)
            if description is not None and isinstance(description, str):
                generator.setDescription(description)
            generator.setResolution(
                svg_dpi
            )  # fixes issues in inkscape of pt size --> 72 pr illustrator and 96 pr inkscape but need change size

            painter = QPainter(generator)

            print(generator.title(), generator.heightMM(), generator.height(),
                  generator.widthMM(), generator.resolution(),
                  generator.description(), generator.logicalDpiX())
        else:
            scaling_factor_dpi = 1
            scaling_factor_dpi = self.scaling_factor_to_achieve_DPI(300)
            image = QtGui.QImage(
                QSize(
                    self.cm_to_inch(21) * dpi * scaling_factor_dpi,
                    self.cm_to_inch(29.7) * dpi * scaling_factor_dpi),
                QtGui.QImage.Format_RGB32)
            painter = QPainter(
                image)  # see what happens in case of rounding of pixels
            painter.scale(scaling_factor_dpi, scaling_factor_dpi)
        painter.setRenderHint(
            QPainter.HighQualityAntialiasing
        )  # to improve rendering #Antialiasing otherwise or nothing
        self.paint(painter)
        painter.end()
        if filetype != 'svg':
            image.save(path)
    def render(self, size):
        image = QImage(size, QImage.Format_ARGB32_Premultiplied)
        if (self.mIncludeBackgroundColor):
            if (self.mMap.backgroundColor().isValid()):
                image.fill(self.mMap.backgroundColor())
            else:
                image.fill(Qt.gray)
        else :
            image.fill(Qt.transparent)
        
        mapSize = self.mRenderer.mapSize()
        margins = self.mRenderer.map().drawMargins()
        mapSize.setWidth(mapSize.width() + margins.left() + margins.right())
        mapSize.setHeight(mapSize.height() + margins.top() + margins.bottom())
        scale = min(size.width() / mapSize.width(), size.height() / mapSize.height())
        scaledSize = mapSize * scale
        painter = QPainter(image)
        # Center the thumbnail in the requested size
        painter.translate((size.width() - scaledSize.width()) / 2,
                          (size.height() - scaledSize.height()) / 2)
        # Scale the map and translate it to adjust for its margins
        painter.scale(scale, scale)
        painter.translate(margins.left() + (size.width() - scaledSize.width()) / 2,
                          margins.top() + (size.height() - scaledSize.height()) / 2)
        if (smoothTransform(scale)):
            painter.setRenderHints(QPainter.SmoothPixmapTransform)
        self.mRenderer.setPainterScale(scale)
        for layer in self.mMap.layers():
            if (self.mVisibleLayersOnly and not layer.isVisible()):
                continue
            painter.setOpacity(layer.opacity())
            tileLayer = dynamic_cast(layer, TileLayer)
            objGroup = dynamic_cast(layer, ObjectGroup)
            imageLayer = dynamic_cast(layer, ImageLayer)
            if (tileLayer):
                self.mRenderer.drawTileLayer(painter, tileLayer)
            elif (objGroup):
                objects = objGroup.objects()
                if (objGroup.drawOrder() == ObjectGroup.TopDownOrder):
                    objects = QList(sorted(objects, key=lambda x:x.y(), reverse=True))
                for object in objects:
                    if (object.isVisible()):
                        if object.rotation() != 0.0:
                            origin = self.mRenderer.pixelToScreenCoords(object.position())
                            painter.save()
                            painter.translate(origin)
                            painter.rotate(object.rotation())
                            painter.translate(-origin)
                        
                        color = MapObjectItem.objectColor(object)
                        self.mRenderer.drawMapObject(painter, object, color)
                        if (object.rotation() != 0):
                            painter.restore()

            elif (imageLayer):
                self.mRenderer.drawImageLayer(painter, imageLayer)

        return image
Exemple #33
0
    def paintEvent(self, e):
        if self.graph:
            painter = QPainter()
            painter.begin(self)
            painter.scale(self.zoom, self.zoom)
            painter.translate(self.delta)

            self.delta.setX = self.start.x()
            self.delta.setY = self.start.y()

            # how scale normalized coordinates
            map_x = self.width() - 2 * self.padding
            map_y = self.height() - 2 * self.padding
            pos = self.graph.pos

            # choose suitable node size
            d = min(int(self.padding * 1.5),
                    int(self.graph.shortest_edge / 2 * min(map_x, map_y)))
            # choose suitable font size
            weight_font_size = int(1 / self.graph.biggest_idx_len * d)
            node_font_size = int(1 / self.graph.biggest_idx_len * d *
                                 self.zoom)
            # qlabel's font size must be greater than 0
            if weight_font_size <= 0:
                weight_font_size = 1
                if node_font_size <= 0:
                    node_font_size = 1

            painter.setPen(QPen(Qt.black, 1 / self.zoom))

            for edge in self.graph.edges:
                p1, p2 = edge.points
                x1, y1, x2, y2 = (pos[p1][0] * map_x + self.padding,
                                  pos[p1][1] * map_y + self.padding,
                                  pos[p2][0] * map_x + self.padding,
                                  pos[p2][1] * map_y + self.padding)
                painter.drawLine(x1, y1, x2, y2)
                lbl = self.edges_to_weights[edge.idx]
                lbl.setFontSize(weight_font_size)
                lbl.move(
                    self.zoom * (x1 + (x2 - x1) // 2 + self.delta.x()) -
                    lbl.width() // 2,
                    self.zoom * (y1 + (y2 - y1) // 2 + self.delta.y()) -
                    lbl.height() // 2)

            painter.setBrush(QBrush(Qt.gray))
            painter.setPen(QPen(Qt.gray))
            for idx, (x, y) in pos.items():
                x = int(x * map_x) + self.padding
                y = int(y * map_y) + self.padding
                painter.drawEllipse(x - d // 2, y - d // 2, d, d)
                lbl = self.points_to_labels[idx]
                lbl.setFontSize(node_font_size)
                lbl.move(self.zoom * (x + self.delta.x()) - lbl.width() // 2,
                         self.zoom * (y + self.delta.y()) - lbl.height() // 2)

            painter.end()
Exemple #34
0
    def paintEvent(self, QPaintEvent):

        painter = QPainter(self)
        painter.translate(600, 100)  # 将(600, 100)设为新图的原点
        # 后四位参素是从图片的(80, 100)位置截取横300,纵100像素的图片,并根据前四位参数对像素图的大小位置设置
        painter.rotate(150)  # 顺时针旋转150度
        painter.scale(2, 2)  # 横纵坐标放大两倍(原点位置不变)
        painter.drawPixmap(0, 0, 300, 200, self.pixmap, 80, 100, 300, 100)
        painter.translate(100, 100)
Exemple #35
0
    def drawBackground(self, painter: QPainter, rect: QRectF):

        # freqs = np.fft.fftfreq(len(w), 1 / self.sample_rate)
        if self.draw_grid and len(self.frequencies) > 0:
            painter.setPen(QPen(painter.pen().color(), 0))
            parent_width = self.parent().width() if hasattr(
                self.parent(), "width") else 750
            view_rect = self.parent().view_rect() if hasattr(
                self.parent(), "view_rect") else rect

            font_width = self.font_metrics.width(
                Formatter.big_value_with_suffix(self.center_freq) + "   ")
            x_grid_size = int(view_rect.width() / parent_width * font_width)
            # x_grid_size = int(0.1 * view_rect.width()) if 0.1 * view_rect.width() > 1 else 1
            y_grid_size = 1
            x_mid = np.where(self.frequencies == 0)[0]
            x_mid = int(x_mid[0]) if len(x_mid) > 0 else 0

            left = int(rect.left()) - (int(rect.left()) % x_grid_size)
            left = left if left > 0 else 0

            top = rect.top() - (rect.top() % y_grid_size)
            bottom = rect.bottom() - (rect.bottom() % y_grid_size)
            right_border = int(
                rect.right()) if rect.right() < len(self.frequencies) else len(
                    self.frequencies)

            x_range = list(range(x_mid, left, -x_grid_size)) + list(
                range(x_mid, right_border, x_grid_size))
            lines = [QLineF(x, rect.top(), x, bottom) for x in x_range] \
                    + [QLineF(rect.left(), y, rect.right(), y) for y in np.arange(top, bottom, y_grid_size)]

            painter.drawLines(lines)
            scale_x, scale_y = util.calc_x_y_scale(rect, self.parent())

            painter.scale(scale_x, scale_y)
            counter = -1  # Counter for Label for every second line

            for x in x_range:
                freq = self.frequencies[x]
                counter += 1

                if freq != 0 and (counter % 2 !=
                                  0):  # Label for every second line
                    continue

                if freq != 0:
                    prefix = "+" if freq > 0 else ""
                    value = prefix + Formatter.big_value_with_suffix(freq, 2)
                else:
                    counter = 0
                    value = Formatter.big_value_with_suffix(6800e6 -
                                                            self.center_freq +
                                                            self.status_k)
                font_width = self.font_metrics.width(value)
                painter.drawText(x / scale_x - font_width / 2,
                                 bottom / scale_y, value)
Exemple #36
0
 def paintEvent(self, e):
     painter = QPainter(self)
     if self.pix != None:
         painter.scale(self.picScale, self.picScale)
         painter.drawPixmap(0, 0, self.pix)
         if self.bDraw:
             painter.setPen(QColor(0, 0, 0))
             painter.drawLine(self.prev_point.x(), 0, self.prev_point.x(),
                              self.height())
             painter.drawLine(0, self.prev_point.y(), self.width(),
                              self.prev_point.y())
             self.setCursor(QCursor(Qt.CrossCursor))
         else:
             self.setCursor(QCursor(Qt.ArrowCursor))
         painter.setPen(self.drawColor)
         if len(self.shapes) > 0:
             for shape in self.shapes:
                 if shape[0] == 'rect':
                     the_rect = bounding_rect(shape[1])
                     painter.drawRect(the_rect[0], the_rect[1],
                                      the_rect[2] - the_rect[0],
                                      the_rect[3] - the_rect[1])
                 elif shape[0] == 'circle':
                     the_rect = bounding_rect(shape[1])
                     painter.drawEllipse(the_rect[0], the_rect[1],
                                         the_rect[2] - the_rect[0],
                                         the_rect[3] - the_rect[1])
                 elif shape[0] == 'poly':
                     for i in range(-1, len(shape[1][0]) - 1):
                         painter.drawLine(shape[1][0][i], shape[1][1][i],
                                          shape[1][0][i + 1],
                                          shape[1][1][i + 1])
         if len(self.current_shape[1][0]) > 0:
             if self.current_shape[0] == 'rect':
                 the_rect = bounding_rect(self.current_shape[1])
                 painter.drawRect(the_rect[0], the_rect[1],
                                  the_rect[2] - the_rect[0],
                                  the_rect[3] - the_rect[1])
             elif self.current_shape[0] == 'circle':
                 the_rect = bounding_rect(self.current_shape[1])
                 painter.drawEllipse(the_rect[0], the_rect[1],
                                     the_rect[2] - the_rect[0],
                                     the_rect[3] - the_rect[1])
             elif self.current_shape[0] == 'poly':
                 if len(self.current_shape[1][0]) > 2:
                     for i in range(0, len(self.current_shape[1][0]) - 1):
                         painter.drawLine(self.current_shape[1][0][i],
                                          self.current_shape[1][1][i],
                                          self.current_shape[1][0][i + 1],
                                          self.current_shape[1][1][i + 1])
                 painter.drawLine(self.current_shape[1][0][0],
                                  self.current_shape[1][1][0],
                                  self.prev_point.x(), self.prev_point.y())
                 painter.drawLine(self.current_shape[1][0][-1],
                                  self.current_shape[1][1][-1],
                                  self.prev_point.x(), self.prev_point.y())
Exemple #37
0
 def getPixmap(self):
     pixmap = QPixmap(self.width * self.pixelRatio,
                      self.height * self.pixelRatio)
     pixmap.setDevicePixelRatio(self.pixelRatio)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.translate(0, self.height)
     painter.scale(1, -1)
     if self.headerAtBottom:
         bodyRect = (0, 0, self.width, self.height - self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     else:
         bodyRect = (0, 0, self.width, self.height - self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     # background
     painter.save()
     if self.headerAtBottom:
         h = self.height
     else:
         h = self.height - self.headerHeight
     painter.translate(0, h)
     painter.scale(1, -1)
     self.drawCellBackground(painter, bodyRect)
     painter.restore()
     # glyph
     if self.headerAtBottom:
         painter.translate(0, self.headerHeight)
     if self.shouldDrawMetrics:
         self.drawCellHorizontalMetrics(painter, bodyRect)
         self.drawCellVerticalMetrics(painter, bodyRect)
     painter.save()
     painter.setClipRect(0, 0, self.width, self.height - self.headerHeight)
     painter.translate(self.xOffset, self.yOffset)
     painter.scale(self.scale, self.scale)
     self.drawCellGlyph(painter)
     painter.restore()
     # foreground
     painter.save()
     painter.translate(0, self.height - self.headerHeight)
     painter.scale(1, -1)
     self.drawCellForeground(painter, bodyRect)
     painter.restore()
     # header
     if self.shouldDrawHeader:
         painter.save()
         if self.headerAtBottom:
             h = 0
         else:
             h = self.height
         painter.translate(0, h)
         painter.scale(1, -1)
         self.drawCellHeaderBackground(painter, headerRect)
         self.drawCellHeaderText(painter, headerRect)
         painter.restore()
     return pixmap
Exemple #38
0
    def paintEvent(self, event):

        p = QPainter()
        p.begin(self)
        p.setRenderHint(QPainter.Antialiasing)
        p.setFont(self._font)
        p.translate(self.width()/2.0, self.height()/2.0)
        p.scale(self._scale, self._scale)
        p.drawText(self._xpos, self._ypos, str(self._value))
        p.end()
 def getPixmap(self):
     pixmap = QPixmap(self.width * self.pixelRatio, self.height * self.pixelRatio)
     pixmap.setDevicePixelRatio(self.pixelRatio)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.translate(0, self.height)
     painter.scale(1, -1)
     if self.headerAtBottom:
         bodyRect = (0, 0, self.width, self.height-self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     else:
         bodyRect = (0, 0, self.width, self.height-self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     # background
     painter.save()
     if self.headerAtBottom:
         h = self.height
     else:
         h = self.height - self.headerHeight
     painter.translate(0, h)
     painter.scale(1, -1)
     self.drawCellBackground(painter, bodyRect)
     painter.restore()
     # glyph
     if self.headerAtBottom:
         painter.translate(0, self.headerHeight)
     if self.shouldDrawMetrics:
         self.drawCellHorizontalMetrics(painter, bodyRect)
         self.drawCellVerticalMetrics(painter, bodyRect)
     painter.save()
     painter.setClipRect(0, 0, self.width, self.height-self.headerHeight)
     painter.translate(self.xOffset, self.yOffset)
     painter.scale(self.scale, self.scale)
     self.drawCellGlyph(painter)
     painter.restore()
     # foreground
     painter.save()
     painter.translate(0, self.height - self.headerHeight)
     painter.scale(1, -1)
     self.drawCellForeground(painter, bodyRect)
     painter.restore()
     # header
     if self.shouldDrawHeader:
         painter.save()
         if self.headerAtBottom:
             h = 0
         else:
             h = self.height
         painter.translate(0, h)
         painter.scale(1, -1)
         self.drawCellHeaderBackground(painter, headerRect)
         self.drawCellHeaderText(painter, headerRect)
         painter.restore()
     return pixmap
Exemple #40
0
    def paintEvent(self, event):

        side = min(self.width(), self.height())
        time = QTime.currentTime()
        time = time.addSecs(self.timeZoneOffset * 3600)

        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(self.hourColor))

        painter.save()
        painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)))
        painter.drawConvexPolygon(self.hourHand)
        painter.restore()

        painter.setPen(self.hourColor)

        for i in range(0, 12):
            painter.drawLine(84, 0, 96, 0)
            painter.rotate(30.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(self.minuteColor))

        painter.save()
        painter.rotate(6.0 * (time.minute() + time.second() / 60.0))
        painter.drawConvexPolygon(self.minuteHand)
        painter.restore()

        painter.setPen(QPen(self.minuteColor))

        for j in range(0, 60):
            if (j % 5) != 0:
                painter.drawLine(90, 0, 96, 0)
            painter.rotate(6.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(self.secondColor))

        painter.save()
        painter.rotate(6.0 * time.second())
        painter.drawConvexPolygon(self.secondHand)
        painter.restore()

        painter.end()
Exemple #41
0
    def drawBackground(self, painter: QPainter, rect: QRectF):
        # freqs = np.fft.fftfreq(len(w), 1 / self.sample_rate)
        if self.draw_grid and len(self.frequencies) > 0:
            painter.setPen(QPen(painter.pen().color(), Qt.FlatCap))
            parent_width = self.parent().width() if hasattr(self.parent(), "width") else 750
            view_rect = self.parent().view_rect() if hasattr(self.parent(), "view_rect") else rect

            font_width = self.font_metrics.width(Formatter.big_value_with_suffix(self.center_freq) + "   ")
            x_grid_size = int(view_rect.width() / parent_width * font_width)
            # x_grid_size = int(0.1 * view_rect.width()) if 0.1 * view_rect.width() > 1 else 1
            y_grid_size = view_rect.height() / parent_width * font_width
            x_mid = np.where(self.frequencies == 0)[0]
            x_mid = int(x_mid[0]) if len(x_mid) > 0 else 0

            left = int(rect.left()) - (int(rect.left()) % x_grid_size)
            left = left if left > 0 else 0

            top = rect.top() - (rect.top() % y_grid_size)
            bottom = rect.bottom() - (rect.bottom() % y_grid_size)
            right_border = int(rect.right()) if rect.right() < len(self.frequencies) else len(self.frequencies)

            x_range = list(range(x_mid, left, -x_grid_size)) + list(range(x_mid, right_border, x_grid_size))
            lines = [QLineF(x, rect.top(), x, bottom) for x in x_range] \
                    + [QLineF(rect.left(), y, rect.right(), y) for y in np.arange(top, bottom, y_grid_size)]

            painter.drawLines(lines)
            scale_x = view_rect.width() / parent_width
            scale_y = view_rect.height() / parent_width
            painter.scale(scale_x, scale_y)

            font_height = self.font_metrics.height()
            counter = -1  # Counter for Label for every second line

            for x in x_range:
                freq =  self.frequencies[x]
                counter += 1

                if freq != 0 and (counter % 2 != 0): # Label for every second line
                    continue

                if freq != 0:
                    prefix = "+" if freq > 0 else ""
                    value = prefix+Formatter.big_value_with_suffix(freq, 2)
                else:
                    counter = 0
                    value = Formatter.big_value_with_suffix(self.center_freq)
                font_width = self.font_metrics.width(value)
                painter.drawText(x / scale_x - font_width / 2,
                                 bottom / scale_y + font_height, value)
Exemple #42
0
def drawTiles(painter, rect, tileSize=6, color=None, backgroundColor=None):
    sz = 2 * tileSize
    tiledPixmap = QPixmap(sz, sz)
    pixmapPainter = QPainter(tiledPixmap)
    pixmapPainter.setPen(Qt.NoPen)
    pixmapPainter.setBrush(Qt.Dense4Pattern)
    brush = pixmapPainter.brush()
    brush.setColor(color)
    pixmapPainter.setBrush(brush)
    pixmapPainter.setBackground(QBrush(backgroundColor))
    pixmapPainter.setBackgroundMode(Qt.OpaqueMode)
    pixmapPainter.scale(tileSize, tileSize)
    pixmapPainter.drawRect(tiledPixmap.rect())
    pixmapPainter.end()
    painter.drawTiledPixmap(rect, tiledPixmap)
Exemple #43
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.scale(self.width() / 100.0, self.height() / 100.0)
        painter.translate(50.0, 50.0)
        painter.rotate(-self.rotationAngle)
        painter.translate(-50.0, -50.0)

        painter.setPen(
                QPen(self.penColor, self.penWidth, Qt.SolidLine, Qt.RoundCap,
                        Qt.RoundJoin))
        gradient = QLinearGradient(0, 0, 0, 100)
        gradient.setColorAt(0.0, self.fillColor1)
        gradient.setColorAt(1.0, self.fillColor2)
        painter.setBrush(QBrush(gradient))
        painter.drawPath(self.path)
Exemple #44
0
    def paintEvent(self, e): 
        time = QTime.currentTime() 
        qp = QPainter()
 
        qp.begin(self)
        #qp.setRenderHint(QPainter.Antialiasing)  # 开启这个抗锯齿,会很占cpu的!
        qp.translate(self.width() / 2, self.height() / 2) 
        qp.scale(self.side / 200.0, self.side / 200.0)
  
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.hourColor)
        qp.save()
        qp.rotate(30.0 * ((time.hour() + time.minute()/ 60.0)))
        qp.drawConvexPolygon(self.hourHand)
        qp.restore()
         
        qp.setPen(self.minuteColor)
        qp.drawText(0,0,"Testdddddddddddddd")
        for i in range(12): 
            qp.drawLine(88, 0, 96, 0)
            qp.rotate(30.0) 
         
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.minuteColor)
        qp.save()
         
        qp.rotate(6.0 * ((time.minute() + (time.second()+time.msec()/1000.0) / 60.0)))
        qp.drawConvexPolygon(self.minuteHand)
        qp.restore()
         
         
        qp.setPen(self.minuteColor)
        for i in range(60): 
            if (i % 5) is not 0:
                qp.drawLine(92, 0, 96, 0)
            qp.rotate(6.0) 
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.secondColor)
        qp.save()
        qp.rotate(6.0*(time.second()+time.msec()/1000.0))
        qp.drawConvexPolygon(self.secondHand)
        qp.restore() 
        qp.end() 
Exemple #45
0
    def createImage(self, transform):
        sx = min(transform.m11(), transform.m22())
        sy = max(transform.m22(), sx)
        fm = QFontMetrics(Colors.headingFont())

        w = fm.width(self.text) + 1
        h = fm.height()
        xShadow = 3.0
        yShadow = 3.0

        image = QImage(int((w + xShadow) * sx), int((h + yShadow) * sy),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(QColor(0, 0, 0, 0).rgba())
        painter = QPainter(image)
        painter.setFont(Colors.headingFont())
        painter.scale(sx, sy)

        # Draw shadow.
        brush_shadow = QLinearGradient(xShadow, yShadow, w, yShadow)
        brush_shadow.setSpread(QLinearGradient.PadSpread)
        if Colors.useEightBitPalette:
            brush_shadow.setColorAt(0.0, QColor(0, 0, 0))
        else:
            brush_shadow.setColorAt(0.0, QColor(0, 0, 0, 100))
        pen_shadow = QPen()
        pen_shadow.setBrush(brush_shadow)
        painter.setPen(pen_shadow)
        painter.drawText(int(xShadow), int(yShadow), int(w), int(h),
                Qt.AlignLeft, self.text)

        # Draw text.
        brush_text = QLinearGradient(0, 0, w, w)
        brush_text.setSpread(QLinearGradient.PadSpread)
        brush_text.setColorAt(0.0, QColor(255, 255, 255))
        brush_text.setColorAt(0.2, QColor(255, 255, 255))
        brush_text.setColorAt(0.5, QColor(190, 190, 190))
        pen_text = QPen()
        pen_text.setBrush(brush_text)
        painter.setPen(pen_text)
        painter.drawText(0, 0, int(w), int(h), Qt.AlignLeft, self.text)

        return image
Exemple #46
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setFont(UIFont)
        painter.setRenderHint(QPainter.Antialiasing)
        rect = event.rect()

        # draw the background
        painter.fillRect(rect, self._backgroundColor)
        if self._glyph is None:
            return

        # apply the overall scale
        painter.save()
        # + translate and flip
        painter.translate(0, self.height())
        painter.scale(self._scale, -self._scale)

        # move into position
        xOffsetInv, yOffsetInv, _, _ = self._drawingRect
        painter.translate(-xOffsetInv, -yOffsetInv)

        # gather the layers
        layerSet = self._glyph.layerSet
        if layerSet is None:
            layers = [(self._glyph, None, True)]
        else:
            glyphName = self._glyph.name
            layers = []
            for layerName in reversed(layerSet.layerOrder):
                layer = layerSet[layerName]
                if glyphName not in layer:
                    continue
                glyph = layer[glyphName]
                layers.append((glyph, layerName, layer == layerSet.defaultLayer))

        self.drawBackground(painter)
        for glyph, layerName, default in layers:
            self.drawGlyphLayer(painter, glyph, layerName, default)
        self.drawForeground(painter)
        painter.restore()
Exemple #47
0
 def paintEvent(self, e):
     p = QPainter(self)
     p.translate(20, 20)
     scale_coef = 1.6
     p.scale(30 * scale_coef, 30 * scale_coef)
     p.setPen(QPen(Qt.black, 0))
     for pin in chain(cpu_pins, mem_pins):
         p.drawEllipse(QPointF(pin.x, pin.y), PIN_RADIUS, PIN_RADIUS)
     for conn_ind, conn in enumerate(connections):
         if conn_ind in max_tail:
             p.setPen(QPen(Qt.red, 0))
         else:
             p.setPen(QPen(Qt.black, 0))
         pin0 = cpu_pins[conn.cpu_pin_idx]
         pin1 = mem_pins[conn.mem_pin_idx]
         p.drawLine(QPointF(pin0.x, pin0.y),
                    QPointF(pin1.x, pin1.y))
     for poly, layer in polygons:
         if layer == 1:
             color = Qt.black
         elif layer == 2:
             color = Qt.red
         elif layer == 2:
             color = Qt.blue
         else:
             assert 0
         color = QColor(color)
         color.setAlpha(180)
         p.setBrush(QBrush(color))
         p.drawPolygon(poly)
     color = QColor(Qt.darkGreen)
     color.setAlpha(180)
     brush = QBrush(color)
     p.setBrush(brush)
     for x, y in jumps:
         # NB jump doesnt have a radius
         p.drawEllipse(QPointF(x, y), PIN_RADIUS, PIN_RADIUS)
         # pass
     p.end()
Exemple #48
0
    def paintEvent(self, event):
        side = min(self.width(), self.height())

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogPosition.positionHandColor)

        painter.save()
        painter.rotate(self.angle)

        painter.drawConvexPolygon(AnalogPosition.positionHand)
        painter.restore()

        painter.setPen(AnalogPosition.positionHandColor)

        for j in range(32):
            painter.drawLine(92, 0, 96, 0)
            painter.rotate(11.25)
Exemple #49
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(self.rect(), Qt.black)

        if self.pixmap.isNull():
            painter.setPen(Qt.white)
            painter.drawText(self.rect(), Qt.AlignCenter,
                    "Rendering initial image, please wait...")
            return

        if self.curScale == self.pixmapScale:
            painter.drawPixmap(self.pixmapOffset, self.pixmap)
        else:
            scaleFactor = self.pixmapScale / self.curScale
            newWidth = int(self.pixmap.width() * scaleFactor)
            newHeight = int(self.pixmap.height() * scaleFactor)
            newX = self.pixmapOffset.x() + (self.pixmap.width() - newWidth) / 2
            newY = self.pixmapOffset.y() + (self.pixmap.height() - newHeight) / 2

            painter.save()
            painter.translate(newX, newY)
            painter.scale(scaleFactor, scaleFactor)
            exposed, _ = painter.matrix().inverted()
            exposed = exposed.mapRect(self.rect()).adjusted(-1, -1, 1, 1)
            painter.drawPixmap(exposed, self.pixmap, exposed)
            painter.restore()

        text = "Use mouse wheel or the '+' and '-' keys to zoom. Press and " \
                "hold left mouse button to scroll."
        metrics = painter.fontMetrics()
        textWidth = metrics.width(text)

        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(0, 0, 0, 127))
        painter.drawRect((self.width() - textWidth) / 2 - 5, 0, textWidth + 10,
                metrics.lineSpacing() + 5)
        painter.setPen(Qt.white)
        painter.drawText((self.width() - textWidth) / 2,
                metrics.leading() + metrics.ascent(), text)
Exemple #50
0
    def paintEvent(self, event):
        side = min(self.width(), self.height())
        time = QTime.currentTime()

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(ShapedClock.hourColor)

        painter.save()
        painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)))
        painter.drawConvexPolygon(ShapedClock.hourHand)
        painter.restore()

        painter.setPen(ShapedClock.hourColor)

        for i in range(12):
            painter.drawLine(88, 0, 96, 0)
            painter.rotate(30.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(ShapedClock.minuteColor)

        painter.save()
        painter.rotate(6.0 * (time.minute() + time.second() / 60.0))
        painter.drawConvexPolygon(ShapedClock.minuteHand)
        painter.restore()

        painter.setPen(ShapedClock.minuteColor)

        for j in range(60):
            if (j % 5) != 0:
                painter.drawLine(92, 0, 96, 0)

            painter.rotate(6.0)
Exemple #51
0
    def printImage(self):
        if self.model.rowCount(QModelIndex()) * self.model.columnCount(QModelIndex()) > 90000:
            answer = QMessageBox.question(self, "Large Image Size",
                    "The printed image may be very large. Are you sure that "
                    "you want to print it?",
                    QMessageBox.Yes | QMessageBox.No)
            if answer == QMessageBox.No:
                return

        printer = QPrinter(QPrinter.HighResolution)

        dlg = QPrintDialog(printer, self)
        dlg.setWindowTitle("Print Image")

        if dlg.exec_() != QDialog.Accepted:
            return

        painter = QPainter()
        painter.begin(printer)

        rows = self.model.rowCount(QModelIndex())
        columns = self.model.columnCount(QModelIndex())
        sourceWidth = (columns+1) * ItemSize
        sourceHeight = (rows+1) * ItemSize

        painter.save()

        xscale = printer.pageRect().width() / float(sourceWidth)
        yscale = printer.pageRect().height() / float(sourceHeight)
        scale = min(xscale, yscale)

        painter.translate(printer.pageRect().x()+printer.pageRect().width()/2,
                          printer.pageRect().y()+printer.pageRect().height()/2)
        painter.scale(scale, scale)
        painter.translate(-sourceWidt/2, -sourceHeight/2)

        option = QStyleOptionViewItem()
        parent = QModelIndex()

        progress = QProgressDialog("Printing...", "Cancel", 0, rows, self)
        y = ItemSize / 2.0

        for row in range(rows):
            progress.setValue(row)
            QApplication.processEvents()
            if progress.wasCanceled():
                break

            x = ItemSize / 2.0

            for col in range(columns):
                option.rect = QRect(x, y, ItemSize, ItemSize)
                self.view.itemDelegate.paint(painter, option,
                        self.model.index(row, column, parent))
                x = x + ItemSize

            y = y + ItemSize

        progress.setValue(rows)

        painter.restore()
        painter.end()

        if progress.wasCanceled():
            QMessageBox.information(self, "Printing canceled",
                    "The printing process was canceled.", QMessageBox.Cancel)
class Renderer:
    def __init__(self, width, height, ownWindow=False):
        self.width = width
        self.height = height

        self.img = QImage(width, height, QImage.Format_RGB888)
        self.painter = QPainter()

        self.window = None
        if ownWindow:
            self.app = QApplication([])
            self.window = Window()

    def close(self):
        """
        Deallocate resources used
        """
        pass

    def beginFrame(self):
        self.painter.begin(self.img)
        self.painter.setRenderHint(QPainter.Antialiasing, False)

        # Clear the background
        self.painter.setBrush(QColor(0, 0, 0))
        self.painter.drawRect(0, 0, self.width - 1, self.height - 1)

    def endFrame(self):
        self.painter.end()

        if self.window:
            if self.window.closed:
                self.window = None
            else:
                self.window.setPixmap(self.getPixmap())
                self.app.processEvents()

    def getPixmap(self):
        return QPixmap.fromImage(self.img)

    def getArray(self):
        """
        Get a numpy array of RGB pixel values.
        The size argument should be (3,w,h)
        """

        width = self.width
        height = self.height
        shape = (width, height, 3)

        numBytes = self.width * self.height * 3
        buf = self.img.bits().asstring(numBytes)
        output = np.frombuffer(buf, dtype='uint8')
        output = output.reshape(shape)

        return output

    def push(self):
        self.painter.save()

    def pop(self):
        self.painter.restore()

    def rotate(self, degrees):
        self.painter.rotate(degrees)

    def translate(self, x, y):
        self.painter.translate(x, y)

    def scale(self, x, y):
        self.painter.scale(x, y)

    def setLineColor(self, r, g, b, a=255):
        self.painter.setPen(QColor(r, g, b, a))

    def setColor(self, r, g, b, a=255):
        self.painter.setBrush(QColor(r, g, b, a))

    def setLineWidth(self, width):
        pen = self.painter.pen()
        pen.setWidthF(width)
        self.painter.setPen(pen)

    def drawLine(self, x0, y0, x1, y1):
        self.painter.drawLine(x0, y0, x1, y1)

    def drawCircle(self, x, y, r):
        center = QPoint(x, y)
        self.painter.drawEllipse(center, r, r)

    def drawPolygon(self, points):
        """Takes a list of points (tuples) as input"""
        points = map(lambda p: QPoint(p[0], p[1]), points)
        self.painter.drawPolygon(QPolygon(points))

    def fillRect(self, x, y, width, height, r, g, b, a=255):
        self.painter.fillRect(QRect(x, y, width, height), QColor(r, g, b, a))
    def exportGeorefRaster(self, layer, rasterPath, isPutRotationInWorldFile):
        rasterFormat = rasterPath[-3:]

        try:
            originalWidth = layer.image.width()
            originalHeight = layer.image.height()
            radRotation = layer.rotation * math.pi / 180

            if isPutRotationInWorldFile:
                # keep the image as is and put all transformation params
                # in world file
                img = layer.image

                a = layer.xScale * math.cos(radRotation)
                # sin instead of -sin because angle in CW
                b = -layer.yScale * math.sin(radRotation)
                d = layer.xScale * -math.sin(radRotation)
                e = -layer.yScale * math.cos(radRotation)
                c = layer.center.x() - (a * (originalWidth - 1) / 2 +
                                        b * (originalHeight - 1) / 2)
                f = layer.center.y() - (d * (originalWidth - 1) / 2 +
                                        e * (originalHeight - 1) / 2)

            else:
                # transform the image with rotation and scaling between the
                # axes
                # maintain at least the original resolution of the raster
                ratio = layer.xScale / layer.yScale
                if ratio > 1:
                    # increase x
                    scaleX = ratio
                    scaleY = 1
                else:
                    # increase y
                    scaleX = 1
                    scaleY = 1. / ratio

                width = (abs(scaleX * originalWidth * math.cos(radRotation)) +
                         abs(scaleY * originalHeight * math.sin(radRotation)))
                height = (abs(scaleX * originalWidth * math.sin(radRotation)) +
                          abs(scaleY * originalHeight * math.cos(radRotation)))

                qDebug("wh %f,%f" % (width, height))

                img = QImage(QSize(math.ceil(width), math.ceil(height)),
                             QImage.Format_ARGB32)
                # transparent background
                img.fill(QColor(0, 0, 0, 0))

                painter = QPainter(img)
                painter.setRenderHint(QPainter.Antialiasing, True)

                rect = QRectF(QPointF(-layer.image.width() / 2.0,
                                      -layer.image.height() / 2.0),
                              QPointF(layer.image.width() / 2.0,
                                      layer.image.height() / 2.0))

                painter.translate(QPointF(width / 2.0, height / 2.0))
                painter.rotate(layer.rotation)
                painter.scale(scaleX, scaleY)
                painter.drawImage(rect, layer.image)
                painter.end()

                extent = layer.extent()
                a = extent.width() / width
                e = -extent.height() / height
                # 2nd term because (0,0) of world file is on center of upper
                # left pixel instead of upper left corner of that pixel
                c = extent.xMinimum() + a / 2
                f = extent.yMaximum() + e / 2
                b = d = 0.0

            img.save(rasterPath, rasterFormat)

            worldFilePath = rasterPath[:-3]
            if rasterFormat == "jpg":
                worldFilePath += "jgw"
            elif rasterFormat == "png":
                worldFilePath += "pgw"
            elif rasterFormat == "bmp":
                worldFilePath += "bpw"
            elif rasterFormat == "tif":
                worldFilePath += "tfw"

            with open(worldFilePath, "w") as writer:
                writer.write("%.13f\n%.13f\n%.13f\n%.13f\n%.13f\n%.13f" %
                             (a, b, d, e, c, f))

            crsFilePath = rasterPath + ".aux.xml"
            with open(crsFilePath, "w") as writer:
                writer.write(self.auxContent(
                    self.iface.mapCanvas().mapSettings().destinationCrs()))

            widget = QgsMessageBar.createMessage(
                "Raster Geoferencer", "Raster exported successfully.")
            self.iface.messageBar().pushWidget(widget,  Qgis.Info, 2)
        except Exception as ex:
            QgsMessageLog.logMessage(repr(ex))
            widget = QgsMessageBar.createMessage(
                "Raster Geoferencer",
                "There was an error performing this command. "
                "See QGIS Message log for details.")
            self.iface.messageBar().pushWidget(
                widget, Qgis.Critical, 5)
Exemple #54
0
    def paintEvent(self, event):
        linePen = QPen(Qt.black)
        linePen.setWidth(3)
        width = self.width() / self.scale

        def paintLineMarks(painter):
            painter.save()
            painter.scale(self.scale, yDirection * self.scale)
            painter.setPen(linePen)
            painter.drawLine(0, self.ascender, width, self.ascender)
            painter.drawLine(0, 0, width, 0)
            painter.drawLine(0, self.descender, width, self.descender)
            painter.restore()

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(0, 0, self.width(), self.height(), Qt.white)
        if self._verticalFlip:
            baselineShift = -self.descender
            yDirection = 1
        else:
            baselineShift = self.ascender
            yDirection = -1
        painter.translate(self.padding, self.padding + baselineShift * self.scale * self._lineHeight)
        # TODO: scale painter here to avoid g*scale everywhere below

        cur_width = 0
        lines = 1
        self._positions = [[]]
        if self._showMetrics:
            paintLineMarks(painter)
        for index, glyph in enumerate(self.glyphs):
            # line wrapping
            gWidth = glyph.width * self.scale
            doKern = index > 0 and self._showKerning and cur_width > 0
            if doKern:
                kern = self.lookupKerningValue(self.glyphs[index - 1].name, glyph.name) * self.scale
            else:
                kern = 0
            if self._wrapLines and cur_width + gWidth + kern + 2 * self.padding > self.width():
                painter.translate(-cur_width, self.ptSize * self._lineHeight)
                if self._showMetrics:
                    paintLineMarks(painter)
                self._positions.append([(0, gWidth)])
                cur_width = gWidth
                lines += 1
            else:
                if doKern:
                    painter.translate(kern, 0)
                self._positions[-1].append((cur_width, gWidth))
                cur_width += gWidth + kern
            glyphPath = glyph.getRepresentation("defconQt.QPainterPath")
            painter.save()
            painter.scale(self.scale, yDirection * self.scale)
            if self._showMetrics:
                halfDescent = self.descender / 2
                painter.drawLine(0, 0, 0, halfDescent)
                painter.drawLine(glyph.width, 0, glyph.width, halfDescent)
            if self._selected is not None and index == self._selected:
                painter.fillRect(0, self.descender, glyph.width, self.upm, glyphSelectionColor)
            painter.fillPath(glyphPath, Qt.black)
            painter.restore()
            painter.translate(gWidth, 0)

        scrollMargins = self._scrollArea.contentsMargins()
        innerHeight = self._scrollArea.height() - scrollMargins.top() - scrollMargins.bottom()
        if not self._wrapLines:
            innerWidth = self._scrollArea.width() - scrollMargins.left() - scrollMargins.right()
            width = max(innerWidth, cur_width + self.padding * 2)
        else:
            width = self.width()
        self.resize(width, max(innerHeight, lines * self.ptSize * self._lineHeight + 2 * self.padding))
Exemple #55
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setFont(headerFont)
        painter.setRenderHint(QPainter.Antialiasing)
        rect = self.rect()

        # draw the background
        painter.fillRect(rect, Qt.white)
        if self._glyph is None:
            return

        # apply the overall scale
        painter.save()
        # + translate and flip
        painter.translate(0, self.height())
        painter.scale(self._scale, -self._scale)

        # move into position
        widgetWidth = self.width()
        width = self._glyph.width * self._scale
        diff = widgetWidth - width
        xOffset = round((diff / 2) * self._inverseScale)

        yOffset = self._verticalCenterYBuffer * self._inverseScale
        yOffset -= self._descender

        painter.translate(xOffset, yOffset)

        # store the current drawing rect
        w, h = self.width(), self.height()
        w *= self._inverseScale
        h *= self._inverseScale
        self._drawingRect = (-xOffset, -yOffset, w, h)

        # gather the layers
        layerSet = self._glyph.layerSet
        if layerSet is None:
            layers = [(self._glyph, None)]
        else:
            glyphName = self._glyph.name
            layers = []
            for layerName in reversed(layerSet.layerOrder):
                layer = layerSet[layerName]
                if glyphName not in layer:
                    continue
                glyph = layer[glyphName]
                if glyph == self._glyph:
                    layerName = None
                layers.append((glyph, layerName))

        for glyph, layerName in layers:
            # draw the image
            if self.drawingAttribute("showGlyphImage", layerName):
                self.drawImage(painter, glyph, layerName)
            # draw the blues
            if layerName is None and self.drawingAttribute(
                    "showFontPostscriptBlues", None):
                self.drawBlues(painter, glyph, layerName)
            if layerName is None and self.drawingAttribute(
                    "showFontPostscriptFamilyBlues", None):
                self.drawFamilyBlues(painter, glyph, layerName)
            # draw the margins
            if self.drawingAttribute("showGlyphMargins", layerName):
                self.drawMargins(painter, glyph, layerName)
            # draw the vertical metrics
            if layerName is None and self.drawingAttribute(
                    "showFontVerticalMetrics", None):
                self.drawVerticalMetrics(painter, glyph, layerName)
            # draw the glyph
            if self.drawingAttribute("showGlyphFill", layerName) or \
                    self.drawingAttribute("showGlyphStroke", layerName):
                self.drawFillAndStroke(painter, glyph, layerName)
            if self.drawingAttribute("showGlyphOnCurvePoints", layerName) or \
                    self.drawingAttribute("showGlyphOffCurvePoints",
                                          layerName):
                self.drawPoints(painter, glyph, layerName)
            if self.drawingAttribute("showGlyphAnchors", layerName):
                self.drawAnchors(painter, glyph, layerName)
        self._currentTool.paint(painter)
        painter.restore()
Exemple #56
0
    def paintEvent(self, event):
        linePen = QPen(Qt.black)
        linePen.setWidth(3)
        width = self.width() / self.scale

        def paintLineMarks(painter):
            painter.save()
            painter.scale(self.scale, yDirection * self.scale)
            painter.setPen(linePen)
            painter.drawLine(0, self.ascender, width, self.ascender)
            painter.drawLine(0, 0, width, 0)
            painter.drawLine(0, self.descender, width, self.descender)
            painter.restore()

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(0, 0, self.width(), self.height(), Qt.white)
        if self._verticalFlip:
            baselineShift = -self.descender
            yDirection = 1
        else:
            baselineShift = self.ascender
            yDirection = -1
        painter.translate(self.padding, self.padding +
                          baselineShift * self.scale * self._lineHeight)
        # TODO: scale painter here to avoid g*scale everywhere below

        cur_width = 0
        if self._showMetrics:
            paintLineMarks(painter)
        for index, glyph in enumerate(self.glyphs):
            # line wrapping
            gWidth = glyph.width * self.scale
            doKern = index > 0 and self._showKerning and cur_width > 0
            if doKern:
                kern = self.lookupKerningValue(
                    self.glyphs[index - 1].name, glyph.name) * self.scale
            else:
                kern = 0
            if (self._wrapLines and cur_width + gWidth + kern +
                    2 * self.padding > self.width()) or glyph.unicode == 2029:
                painter.translate(-cur_width, self.ptSize * self._lineHeight)
                if self._showMetrics:
                    paintLineMarks(painter)
                cur_width = gWidth
            else:
                if doKern:
                    painter.translate(kern, 0)
                cur_width += gWidth + kern
            glyphPath = glyph.getRepresentation("defconQt.QPainterPath")
            painter.save()
            painter.scale(self.scale, yDirection * self.scale)
            if self._showMetrics:
                halfDescent = self.descender / 2
                painter.drawLine(0, 0, 0, halfDescent)
                painter.drawLine(glyph.width, 0, glyph.width, halfDescent)
            if self._selected is not None and index == self._selected:
                painter.fillRect(0, self.descender, glyph.width,
                                 self.upm, glyphSelectionColor)
            painter.fillPath(glyphPath, Qt.black)
            painter.restore()
            painter.translate(gWidth, 0)
Exemple #57
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        redrawRect = event.rect()
        beginRow = redrawRect.top() // self.squareSize
        endRow = redrawRect.bottom() // self.squareSize
        # XXX: do we need to maintain self._column when we have (endColumn -
        # beginColumn)?
        beginColumn = redrawRect.left() // self.squareSize
        endColumn = redrawRect.right() // self.squareSize

        gradient = QLinearGradient(0, 0, 0, GlyphCellHeaderHeight)
        gradient.setColorAt(0.0, cellHeaderBaseColor)
        gradient.setColorAt(1.0, cellHeaderLineColor)
        dirtyGradient = QLinearGradient(0, 0, 0, GlyphCellHeaderHeight)
        dirtyGradient.setColorAt(0.0, cellHeaderBaseColor.darker(125))
        dirtyGradient.setColorAt(1.0, cellHeaderLineColor.darker(125))
        markGradient = QLinearGradient(0, 0, 0, self.squareSize-GlyphCellHeaderHeight)

        for row in range(beginRow, endRow + 1):
            for column in range(beginColumn, endColumn + 1):
                key = row * self._columns + column
                if key >= len(self._glyphs): break
                glyph = self._glyphs[key]

                painter.save()
                painter.translate(column * self.squareSize, row * self.squareSize)
                painter.fillRect(0, 0, self.squareSize, self.squareSize, Qt.white)
                # prepare header colors
                brushColor = gradient
                linesColor = cellHeaderHighlightLineColor
                # mark color
                if not glyph.template:
                    if glyph.markColor is not None:
                        markColor = QColor.fromRgbF(*tuple(glyph.markColor))
                        markGradient.setColorAt(1.0, markColor)
                        markGradient.setColorAt(0.0, markColor.lighter(125))
                        painter.fillRect(0, GlyphCellHeaderHeight, self.squareSize,
                              self.squareSize - GlyphCellHeaderHeight, QBrush(markGradient))
                    if glyph.dirty:
                        brushColor = dirtyGradient
                        linesColor = cellHeaderHighlightLineColor.darker(110)

                # header gradient
                painter.fillRect(0, 0, self.squareSize, GlyphCellHeaderHeight,
                    QBrush(brushColor))
                # header lines
                painter.setPen(linesColor)
                minOffset = painter.pen().width()
                # disable antialiasing to avoid lines bleeding over background
                painter.setRenderHint(QPainter.Antialiasing, False)
                painter.drawLine(0, 0, 0, GlyphCellHeaderHeight - 1)
                painter.drawLine(self.squareSize - 2, 0, self.squareSize - 2, GlyphCellHeaderHeight -1)
                painter.setPen(QColor(170, 170, 170))
                painter.drawLine(0, GlyphCellHeaderHeight, self.squareSize, GlyphCellHeaderHeight)
                painter.setRenderHint(QPainter.Antialiasing)
                # header text
                painter.setFont(headerFont)
                painter.setPen(QColor(80, 80, 80))
                name = metrics.elidedText(glyph.name, Qt.ElideRight, self.squareSize - 2)
                painter.drawText(1, 0, self.squareSize - 2, GlyphCellHeaderHeight - minOffset,
                      Qt.TextSingleLine | Qt.AlignCenter, name)
                painter.restore()

                painter.setPen(cellGridColor)
                rightEdgeX = column * self.squareSize + self.squareSize
                bottomEdgeY = row * self.squareSize + self.squareSize
                painter.drawLine(rightEdgeX, row * self.squareSize + 1, rightEdgeX, bottomEdgeY)
                painter.drawLine(rightEdgeX, bottomEdgeY, column * self.squareSize + 1, bottomEdgeY)
                if self._currentDropIndex is not None:
                    painter.setPen(Qt.green)
                    if self._currentDropIndex == key:
                        painter.drawLine(column * self.squareSize, row * self.squareSize,
                            column * self.squareSize, bottomEdgeY)
                    # special-case the end-column
                    elif column == endColumn and self._currentDropIndex == key+1:
                        yPos = self.mapFromGlobal(QCursor.pos()).y()
                        if row == yPos // self.squareSize:
                            painter.drawLine(rightEdgeX - 1, row * self.squareSize,
                                rightEdgeX - 1, bottomEdgeY)

                # selection code
                if key in self._selection:
                    painter.setRenderHint(QPainter.Antialiasing, False)
                    painter.fillRect(column * self.squareSize + 1,
                            row * self.squareSize + 1, self.squareSize - 3,
                            self.squareSize - 3, cellSelectionColor)
                    painter.setRenderHint(QPainter.Antialiasing)

                if not glyph.template:
                    font = glyph.getParent()
                    outline = glyph.getRepresentation("defconQt.QPainterPath")
                    uPM = font.info.unitsPerEm
                    if uPM is None or not uPM > 0:
                        uPM = 1000
                    descender = font.info.descender
                    if descender is None or not descender < 0:
                        descender = -250
                    factor = (self.squareSize-GlyphCellHeaderHeight) / (uPM*(1+2*GlyphCellBufferHeight))
                    x_offset = (self.squareSize-glyph.width*factor)/2
                    # If the glyph overflows horizontally we need to adjust the scaling factor
                    if x_offset < 0:
                        factor *= 1+2*x_offset/(glyph.width*factor)
                        x_offset = 0
                    # TODO: the * 1.8 below is somewhat artificial
                    y_offset = descender*factor * 1.8
                    painter.save()
                    painter.setClipRect(column * self.squareSize, row * self.squareSize+GlyphCellHeaderHeight,
                          self.squareSize, self.squareSize-GlyphCellHeaderHeight)
                    painter.translate(column * self.squareSize + x_offset, row * self.squareSize + self.squareSize + y_offset)
                    painter.scale(factor, -factor)
                    painter.fillPath(outline, Qt.black)
                    painter.restore()
                else:
                    painter.save()
                    painter.setFont(voidFont)
                    painter.setPen(QPen(Qt.lightGray))
                    rect = QRectF(column * self.squareSize, row * self.squareSize+GlyphCellHeaderHeight,
                          self.squareSize, self.squareSize-GlyphCellHeaderHeight)
                    # TODO: need to flag template glyphs as to whether they have unicodings or not
                    if glyph.unicode is not None:
                        text = chr(glyph.unicode)
                    else:
                        text = "✌"
                    painter.drawText(rect, Qt.AlignCenter, text)
                    painter.restore()