def seed_img(self, is_seed = True): if is_seed: try: cseed = self.get_seed() except UserCancelled: return except InvalidPassword as e: self.d.show_error(str(e)) return if not cseed: self.d.show_message(_("This wallet has no seed")) return txt = cseed.upper() else: txt = self.txt.upper() img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono) bitmap = QBitmap.fromImage(img, Qt.MonoOnly) bitmap.fill(Qt.white) painter = QPainter() painter.begin(bitmap) QFontDatabase.addApplicationFont(os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf') ) if len(txt) < 102 : fontsize = 15 linespace = 15 max_letters = 17 max_lines = 6 max_words = 3 else: fontsize = 12 linespace = 10 max_letters = 21 max_lines = 9 max_words = int(max_letters/4) font = QFont('Source Sans Pro', fontsize, QFont.Bold) font.setLetterSpacing(QFont.PercentageSpacing, 100) font.setPixelSize(fontsize) painter.setFont(font) seed_array = txt.split(' ') for n in range(max_lines): nwords = max_words temp_seed = seed_array[:nwords] while len(' '.join(map(str, temp_seed))) > max_letters: nwords = nwords - 1 temp_seed = seed_array[:nwords] painter.drawText(QRect(0, linespace*n , self.SIZE[0], self.SIZE[1]), Qt.AlignHCenter, ' '.join(map(str, temp_seed))) del seed_array[:nwords] painter.end() img = bitmap.toImage() if (self.rawnoise == False): self.make_rawnoise() self.make_cypherseed(img, self.rawnoise, False, is_seed) return img
def _redrawColorLabel(self, labelIndex, lc, uc, lValue, uValue) : if labelIndex >= len(self.__colorLabels) : return label = self.__colorLabels[labelIndex] pixmap = QPixmap(101, 26) painter = QPainter(pixmap) lowerColorRect = QRect(0, 0, 50, 25) upperColorRect = QRect(50, 0, 50, 25) font = QFont('Times', 11) painter.setFont(font) painter.setPen(Qt.black); painter.setBrush(lc); painter.drawRect(lowerColorRect); painter.setPen(self.invert(lc)); painter.drawText(lowerColorRect.translated(8, 2), 0, str(lValue)); painter.setPen(Qt.black); painter.setBrush(uc); painter.drawRect(upperColorRect); painter.setPen(self.invert(uc)); painter.drawText(upperColorRect.translated(8, 2), 0, str(uValue)); del painter label.setPixmap(pixmap);
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
def lineNumberAreaPaintEvent(self, event): painter = QPainter(self.lineNumbers) painter.fillRect(event.rect(), QColor(230, 230, 230)) d = event.rect().topRight() a = event.rect().bottomRight() painter.setPen(Qt.darkGray) painter.drawLine(d.x(), d.y(), a.x(), a.y()) painter.setPen(QColor(100, 100, 100)) painter.setFont(self.font()) block = self.firstVisibleBlock() blockNumber = block.blockNumber() top = int( self.blockBoundingGeometry(block).translated( self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): number = str(blockNumber + 1) painter.drawText(4, top, self.lineNumbers.width() - 8, self.fontMetrics().height(), Qt.AlignRight, number) block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) blockNumber += 1
def _get_pos_widget(name, backgroundColor, foregroundColor): label = QLabel() label.setAttribute(Qt.WA_TransparentForMouseEvents, True) pixmap = QPixmap(25 * 10, 25 * 10) pixmap.fill(backgroundColor) painter = QPainter() painter.begin(pixmap) pen = QPen(foregroundColor) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing) font = QFont() font.setBold(True) font.setPixelSize(25 * 10 - 30) path = QPainterPath() path.addText(QPointF(50, 25 * 10 - 50), font, name) brush = QBrush(foregroundColor) painter.setBrush(brush) painter.drawPath(path) painter.setFont(font) painter.end() pixmap = pixmap.scaled(QSize(20, 20), Qt.KeepAspectRatio, Qt.SmoothTransformation) label.setPixmap(pixmap) spinbox = DelayedSpinBox(750) spinbox.setAlignment(Qt.AlignCenter) spinbox.setToolTip("{0} Spin Box".format(name)) spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons) spinbox.setMaximumHeight(20) font = spinbox.font() font.setPixelSize(14) spinbox.setFont(font) sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name()) spinbox.setStyleSheet(sheet) return label, spinbox
def paintEvent(self, event): # Check whether this orb is enhanced if type(self.parent) == Board: enh = self.parent.enhanced[self.position] else: enh = False painter = QPainter(self) painter.drawPixmap(event.rect().adjusted(2,2,-2,-2), self.pixmap()) w = event.rect().width() if enh: path = QPainterPath() pen = QPen() pen.setWidth(1); pen.setBrush(Qt.white) brush = QBrush(Qt.yellow) font = QFont() font.setPointSize(20) font.setWeight(QFont.Black) path.addText(event.rect().x()+w-15,event.rect().y()+w-5,font,'+') painter.setPen(pen) painter.setBrush(brush) painter.setFont(font) painter.drawPath(path)
def __init__(self, text, parent): super(DragLabel, self).__init__(parent) metric = QFontMetrics(self.font()) size = metric.size(Qt.TextSingleLine, text) image = QImage(size.width() + 12, size.height() + 12, QImage.Format_ARGB32_Premultiplied) image.fill(qRgba(0, 0, 0, 0)) font = QFont() font.setStyleStrategy(QFont.ForceOutline) painter = QPainter() painter.begin(image) painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(Qt.white) painter.drawRoundedRect(QRectF(0.5, 0.5, image.width() - 1, image.height() - 1), 25, 25, Qt.RelativeSize) painter.setFont(font) painter.setBrush(Qt.black) painter.drawText(QRect(QPoint(6, 6), size), Qt.AlignCenter, text) painter.end() self.setPixmap(QPixmap.fromImage(image)) self.labelText = text
def paintEvent(self, event): painter = QPainter(self) font = painter.font() font.setPointSize(self.width() / 6.0) painter.setFont(font) painter.drawText(self.rect(), Qt.AlignCenter | Qt.AlignVCenter, str(self.value())) QDial.paintEvent(self, event)
def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self) width = self.width() - self.RIGHT_MARGIN - self.LEFT_MARGIN height = self._neditor.fontMetrics().height() font = self._neditor.font() font_bold = self._neditor.font() font_bold.setBold(True) pen = QPen(self._color_unselected) painter.setPen(pen) painter.setFont(font) sel_start, sel_end = self._neditor.selection_range() has_sel = sel_start != sel_end current_line, _ = self._neditor.cursor_position # Draw visible blocks for top, line, block in self._neditor.visible_blocks: # Set bold to current line and selected lines if ((has_sel and sel_start <= line <= sel_end) or (not has_sel and current_line == line)): painter.fillRect( QRect(0, top, self.width(), height), self._color_selected) else: painter.setPen(pen) painter.setFont(font) painter.drawText(self.LEFT_MARGIN, top, width, height, Qt.AlignRight, str(line + 1))
def lineNumberAreaPaintEvent(self, event): # When text zoomed line number not zoomed """Painting line number area""" painter = QPainter(self.lineNumberArea) painter.fillRect(event.rect(), Qt.lightGray) block = self.firstVisibleBlock() blockNumber = block.blockNumber() top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top()) bottom = top + int(self.blockBoundingRect(block).height()) # font_height = self.fontMetrics().height() while block.isValid() and top <= event.rect().bottom(): if block.isVisible() and bottom >= event.rect().top(): font_original = self.document().defaultFont() size = font_original.pointSize() font = painter.font() font.setPointSize(size) painter.setFont(font) number = str(blockNumber + 1) painter.setPen(Qt.black) painter.drawText(0, top, self.lineNumberArea.width(), self.fontMetrics().height(), Qt.AlignRight, number) block = block.next() top = bottom bottom = top + int(self.blockBoundingRect(block).height()) blockNumber += 1
def __redrawColorLabel(self, label, lc, uc): pixmap = QPixmap(101, 26) painter = QPainter(pixmap) lowerColorRect = QRect(0, 0, 50, 25) upperColorRect = QRect(50, 0, 50, 25) font = QFont("Times", 11) painter.setFont(font) painter.setPen(Qt.black) painter.setBrush(lc) painter.drawRect(lowerColorRect) lgray = lc.red() + lc.green() + lc.blue() painter.setPen(self.invert(lc)) painter.drawText(lowerColorRect.translated(8, 2), 0, str(lgray)) painter.setPen(Qt.black) painter.setBrush(uc) painter.drawRect(upperColorRect) ugray = uc.red() + uc.green() + uc.blue() painter.setPen(self.invert(uc)) painter.drawText(upperColorRect.translated(8, 2), 0, str(ugray)) del painter label.setPixmap(pixmap)
def drawROIBoxes(self, image): #print(self.frame_data) if not isinstance(self.frame_data, pd.DataFrame) or len(self.frame_data) == 0 \ or not self.label_type in self.frame_data: return self.img_h_ratio = image.height()/self.image_height; self.img_w_ratio = image.width()/self.image_width; painter = QPainter() painter.begin(image) for row_id, row_data in self.frame_data.iterrows(): x = row_data['coord_x']*self.img_h_ratio y = row_data['coord_y']*self.img_w_ratio #check if the coordinates are nan if not (x == x) or not (y == y): continue x = int(x) y = int(y) c = self.wlabC[int(row_data[self.label_type])] painter.setPen(c) painter.setFont(QFont('Decorative', 10)) painter.drawText(x, y, str(int(row_data[self.worm_index_type]))) bb = row_data['roi_size']*self.img_w_ratio painter.drawRect(x-bb/2, y-bb/2, bb, bb); painter.end()
def draw_indicator(indicator: int): pixmap = QPixmap(24, 24) painter = QPainter(pixmap) w, h = pixmap.width(), pixmap.height() painter.fillRect(0, 0, w, h, QBrush((QColor(0, 0, 200, 255)))) pen = QPen(QColor("white")) pen.setWidth(2) painter.setPen(pen) font = util.get_monospace_font() font.setBold(True) font.setPixelSize(16) painter.setFont(font) f = QFontMetrics(painter.font()) indicator_str = str(indicator) if indicator < 10 else "+" fw = f.width(indicator_str) fh = f.height() painter.drawText(math.ceil(w / 2 - fw / 2), math.ceil(h / 2 + fh / 4), indicator_str) painter.end() return QIcon(pixmap)
def paintEvent(self, event): painter = QPainter(self) rect = event.rect() rect.setWidth(self.__width()) painter.fillRect(rect, self._background_color) painter.setPen(Qt.white) font = self._console_widget.font() painter.setFont(font) width = self.__width() height = self._console_widget.fontMetrics().height() for top, line, block in self._console_widget.visible_blocks: data = self.user_data(block) prompt = data.get("prompt") text = self.PROMPT_IN color = Qt.white if prompt is not None: if prompt == self.PROMPT_INCOMPLETE: text = self.PROMPT_INCOMPLETE color = Qt.yellow else: text = self.PROMPT_OUT color = Qt.gray painter.setPen(color) painter.drawText(0, top, width, height, Qt.AlignCenter, text)
def paintEvent(self, event): painter = QPainter(self) event.accept() if not self.isEnabled(): painter.save() painter.setOpacity(0.2) painter.drawPixmap(self.fPixmapRect, self.fPixmapNormal, self.fPixmapRect) painter.restore() elif self.isChecked() or self.isDown(): painter.drawPixmap(self.fPixmapRect, self.fPixmapDown, self.fPixmapRect) elif self.fIsHovered: painter.drawPixmap(self.fPixmapRect, self.fPixmapHover, self.fPixmapRect) else: painter.drawPixmap(self.fPixmapRect, self.fPixmapNormal, self.fPixmapRect) if not self.fTopText: return painter.save() painter.setPen(self.fTopTextColor) painter.setBrush(self.fTopTextColor) painter.setFont(self.fTopTextFont) painter.drawText(QPointF(10, 16), self.fTopText) painter.restore()
def paintEvent(self, event): # the original code tried to be clever about painting an caching. it # only painted the screen if it was dirty. for the redraws when the # dirty flag was not set it relyed on the OS not the clear the cash. # but this does not work (at least on macOS). instead of caching in # the OS cache the screen in a pixmap to have full control over it if self._pixmap == None or self.size() != self._pixmap.size(): self._pixmap = QPixmap(self.size()) self._dirty = True if self._dirty: self._dirty = False pixmap_painter = QPainter(self._pixmap) pixmap_painter.setFont(self.font()) self._paint_screen(pixmap_painter) painter = QPainter(self) painter.drawPixmap(0, 0, self._pixmap) # We don't use the blinky cursor for now # if self._cursor_rect is not None and self._selection is None: # self._paint_cursor(painter) if self._selection: self._paint_selection(painter) self._dirty = True
def paintEvent(self, event): painter = QPainter(self) self.font.setPixelSize(self.height() - self.padding * 2) painter.setPen(QtGui.QColor(19, 125, 17, 255)) painter.setFont(self.font) painter.drawText(0, 0, self.width(), self.height(), QtCore.Qt.AlignRight, self.info_string) painter.end()
def image(cls, **kwargs): """ Returns an image suitable for the palette. :rtype: QPixmap """ # INITIALIZATION pixmap = QPixmap(kwargs['w'], kwargs['h']) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) # INITIALIZE EDGE LINE pp1 = QPointF(((kwargs['w'] - 52) / 2), kwargs['h'] / 2) pp2 = QPointF(((kwargs['w'] - 52) / 2) + 52 - 2, kwargs['h'] / 2) line = QLineF(pp1, pp2) # CALCULATE HEAD COORDINATES angle = radians(line.angle()) p1 = QPointF(line.p2().x() + 2, line.p2().y()) p2 = p1 - QPointF(sin(angle + M_PI / 3.0) * 8, cos(angle + M_PI / 3.0) * 8) p3 = p1 - QPointF(sin(angle + M_PI - M_PI / 3.0) * 8, cos(angle + M_PI - M_PI / 3.0) * 8) # INITIALIZE EDGE HEAD head = QPolygonF([p1, p2, p3]) # DRAW THE POLYGON painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(line) # DRAW HEAD painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.setBrush(QColor(0, 0, 0)) painter.drawPolygon(head) # DRAW THE TEXT ON TOP OF THE EDGE space = 2 if Platform.identify() is Platform.Darwin else 0 painter.setFont(Font('Arial', 9, Font.Light)) painter.drawText(pp1.x() + space, (kwargs['h'] / 2) - 4, 'instanceOf') return pixmap
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 paint_metadata(self, painter: QPainter) -> None: font = self.style.font fm = self.style.fm painter.setFont(font) if self.new: painter.drawPixmap(QRect(2, 2, 24, 24), self.style.shared_pixmaps.new) if "type" in self.fileinfo.metadata() and self.fileinfo.metadata()["type"] == "error": painter.drawPixmap(QRect(2, 2, 24, 24), self.style.shared_pixmaps.error) top_left_text, top_right_text, bottom_left_text, bottom_right = self.make_text() if top_left_text: w = fm.width(top_left_text) painter.setPen(Qt.NoPen) painter.setBrush(QColor(255, 255, 255, 160)) painter.drawRect(0, 0, w + 4, 16) painter.setPen(QColor(0, 0, 0)) painter.drawText(2, 12, top_left_text) if top_right_text: w = fm.width(top_right_text) painter.setPen(Qt.NoPen) painter.setBrush(QColor(255, 255, 255, 160)) painter.drawRect(self.thumbnail_rect.width() - w - 4, 0, w + 4, 16) painter.setPen(QColor(0, 0, 0)) painter.drawText(self.thumbnail_rect.width() - w - 2, 12, top_right_text) if bottom_left_text: w = fm.width(bottom_left_text) painter.setPen(Qt.NoPen) painter.setBrush(QColor(255, 255, 255, 160)) painter.drawRect(0, self.thumbnail_rect.height() - 16, w + 4, 16) painter.setPen(QColor(0, 0, 0)) painter.drawText(2, self.thumbnail_rect.height() - 4, bottom_left_text) if self.fileinfo.is_video(): painter.setOpacity(0.5) # painter.setCompositionMode(QPainter.CompositionMode_Plus) painter.drawPixmap(QRect(self.thumbnail_rect.width() - 24 - 2, self.thumbnail_rect.height() - 24 - 2, 24, 24), self.style.shared_pixmaps.video) painter.setOpacity(1.0) elif self.fileinfo.is_image(): painter.setOpacity(0.5) # painter.setCompositionMode(QPainter.CompositionMode_Plus) painter.drawPixmap(QRect(self.thumbnail_rect.width() - 24 - 2, self.thumbnail_rect.height() - 24 - 2, 24, 24), self.style.shared_pixmaps.image) painter.setOpacity(1.0)
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setFont(self.font()) if self._lineMode == 1: self.drawText(painter, self.text, self.percentage) if self._lineMode == 2: self.drawText(painter, self.line1_text, self.line1_percentage, mode="Double", lineMode=1) self.drawText(painter, self.line2_text, self.line2_percentage, mode="Double", lineMode=2) super(DLrcText, self).paintEvent(event)
def draw(self, painter: QPainter): if not self._visible: return bg_brush = QBrush(self._bgcolor, Qt.SolidPattern) b_rect = self._fm.boundingRect(self._text) b_rect.adjust(0, 0, self._margin, self._margin) b_rect.moveTo(self._x, self._y) painter.setPen(self._frame_color) painter.setBrush(bg_brush) painter.drawRect(b_rect) painter.setPen(self._text_color) painter.setFont(self._font) painter.drawText(b_rect, Qt.AlignCenter, self._text)
def paintEvent(self, event): # Init painter. painter = QPainter(self) painter.save() # Draw background. painter.setBrush(self.background_color) painter.setPen(self.background_color) painter.drawRect(0, 0, self.rect().width(), self.rect().height()) # Get start/last render index. start_page_index = self.get_start_page_index() last_page_index = self.get_last_page_index() # Translate painter at y coordinate. translate_y = (start_page_index * self.scale * self.page_height) - self.scroll_offset painter.translate(0, translate_y) # Render pages in visible area. for index in list(range(start_page_index, last_page_index)): if index < self.page_total_number: # Get page image. qpixmap = self.get_page_pixmap(index, self.scale) # Init render rect. render_width = self.page_width * self.scale render_height = self.page_height * self.scale render_x = (self.rect().width() - render_width) / 2 render_y = (index - start_page_index) * self.scale * self.page_height # Add padding between pages. if (index - start_page_index) > 0: painter.translate(0, self.page_padding) # Draw page image. painter.drawPixmap(QRect(render_x, render_y, render_width, render_height), qpixmap) # Clean unused pixmap cache that avoid use too much memory. self.clean_unused_page_cache_pixmap() painter.restore() # Render current page. painter.setFont(self.font) painter.setPen(self.page_annotate_color) painter.drawText(QRect(self.rect().x(), self.rect().y() + self.rect().height() - self.page_annotate_height - self.page_annotate_padding_bottom, self.rect().width() - self.page_annotate_padding_right, self.page_annotate_height), Qt.AlignRight, "{0}% ({1}/{2})".format(int((start_page_index + 1) * 100 / self.page_total_number), start_page_index + 1, self.page_total_number))
def paintEvent(self, paintEvent): """ Executed when the splashscreen needs to be painted. :type paintEvent: QPaintEvent """ super().paintEvent(paintEvent) painter = QPainter(self) painter.setFont(Font('Arial', 12, Font.Light)) ## BOUNDING RECT (0, 194, 400, 86) painter.setPen(QPen(QColor(212, 212, 212), 1.0, Qt.SolidLine)) painter.drawText(QRect(0, 202, 396, 14), Qt.AlignTop|Qt.AlignRight, '{} v{}'.format(APPNAME, VERSION)) painter.drawText(QRect(0, 216, 396, 14), Qt.AlignTop|Qt.AlignRight, COPYRIGHT) painter.drawText(QRect(0, 230, 396, 14), Qt.AlignTop|Qt.AlignRight, 'Licensed under the GNU GPL v3') painter.drawText(QRect(0, 258, 396, 14), Qt.AlignTop|Qt.AlignRight, 'Starting up...')
def _drawTextShadow(self, painter: QPainter, x: int, y: int, text: str): font = self.font() # setup outline path text_path = QPainterPath() text_path.addText(x, y, font, text) # draw outline path 1 painter.setPen(self.outline_pen) painter.setBrush(self.outline_brush) painter.drawPath(text_path) # draw text painter.setPen(self.text_color) painter.setFont(font) # Note: The y-position is used as the baseline of the font. painter.drawText(x, y, text)
def fontValuePixmap(font): f = QFont(font) img = QImage(16, 16, QImage.Format_ARGB32_Premultiplied) img.fill(0) p = QPainter(img) p.setRenderHint(QPainter.TextAntialiasing, True) p.setRenderHint(QPainter.Antialiasing, True) f.setPointSize(13) p.setFont(f) t = QTextOption() t.setAlignment(Qt.AlignCenter) p.drawText(QRectF(0, 0, 16, 16), 'A', t) p.end() return QPixmap.fromImage(img)
def font_charBmp(font, char): metric = QFontMetrics( font ).boundingRect( char ) char_rect = QRect( 0, 0, metric.width(), metric.height() ) chr_img = QImage( char_rect.width()+1, char_rect.height(), QImage.Format_Mono ) chr_img.fill(0) # set img painter and draw char to bmp painter = QPainter( chr_img ) painter.setPen( QPen(Qt.white) ) painter.setFont( font ) painter.drawText( char_rect, Qt.AlignJustify, char ) painter.end() del(painter) # crop left / right x0 = 0 x1 = char_rect.width() while x0 < x1 - 1: data_col = 0 for col in range( char_rect.height() ): data_col += chr_img.pixel(x0, col) & 0x00FFFFFF if not data_col: x0 += 1 else: break char_rect.setX(x0) while x1 > x0 + 1: x1 -= 1 data_col = 0 for col in range( char_rect.height() ): data_col += chr_img.pixel(x1, col) & 0x00FFFFFF if not data_col: char_rect.setWidth(x1 - x0) else: break # crop bottom y1 = char_rect.height() while y1 > 1: y1 -= 1 data_row = 0 for row in range( char_rect.width() ): data_row += chr_img.pixel(row, y1) & 0x00FFFFFF if not data_row: char_rect.setHeight(y1) else: break chr_img = chr_img.copy( char_rect ) # chr_img.save( '.\\img\\0%s.bmp' % char, 'bmp' ) return chr_img
def _drawOutlinedText(painter: QPainter, x: int, y: int, text: str, font: QFont, textColor: QColor, outlineColor: QColor, outlineWidth: int=1): # setup outline path text_path = QPainterPath() text_path.addText(x, y, font, text) # draw outline path outlineBrush = QBrush(outlineColor, Qt.SolidPattern) outlinePen = QPen(outlineBrush, outlineWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) painter.setPen(outlinePen) painter.setBrush(outlineBrush) painter.drawPath(text_path) # draw text painter.setPen(textColor) painter.setFont(font) painter.drawText(x, y, text)
def paintEvent(self,e): # print(e) linear_gradient = QLinearGradient() linear_gradient.setStart(0, 10) #填充的起点坐标 linear_gradient.setFinalStop(0, 40) #填充的终点坐标 #第一个参数终点坐标,相对于我们上面的区域而言,按照比例进行计算 linear_gradient.setColorAt(0.1, QColor(14, 179, 255)) linear_gradient.setColorAt(0.5, QColor(114, 232, 255)) linear_gradient.setColorAt(0.9, QColor(14, 179, 255)) mask_linear_gradient = QLinearGradient() #遮罩的线性渐变填充 mask_linear_gradient.setStart(0, 10) mask_linear_gradient.setFinalStop(0, 40) # mask_linear_gradient.setColorAt(0.1, QColor(254, 113, 122)) # mask_linear_gradient.setColorAt(0.3, QColor(224, 246, 242)) mask_linear_gradient.setColorAt(0.1, QColor(14, 179, 255)) mask_linear_gradient.setColorAt(0.5, QColor(114, 232, 255)) # mask_linear_gradient.setColorAt(0.5, QColor(253, 147, 255)) # mask_linear_gradient.setColorAt(0.7, QColor(1, 1, 1)) # mask_linear_gradient.setColorAt(0.7, QColor(64, 2, 2)) mask_linear_gradient.setColorAt(0.9, QColor(14, 179, 255)) # mask_linear_gradient.setColorAt(1, QColor(0, 0, 0)) # print(e) # 设置字体 font = QFont() font.setFamily("文泉驿等宽微米黑") font.setBold(True) font.setPointSize(30) # self.q.setFont(font) p = QPainter(self) p.setFont(font); # p.setPen(QColor(0, 0, 0, 200)); # p.drawText(1, 1, 700, 60, Qt.AlignHCenter, "梦音乐梦音乐梦音乐"); #//左对齐 # // 再在上面绘制渐变文字 # p.setPen(QPen(linear_gradient, 0)); # p.drawText(0, 0, 800, 60, Qt.AlignHCenter, "梦音乐梦音乐梦音乐"); # SYL - 让我们用声音聆听彼此~ # if not self.s: # self.s = str("SYL - 让我们用声音聆听彼此~") # // 设置歌词遮罩 p.setPen(QPen(mask_linear_gradient, 0)); p.drawText(0, 0, 900, 60, Qt.AlignHCenter, self.text());
def __print(self, printer): """ Private slot to the actual printing. @param printer reference to the printer object (QPrinter) """ painter = QPainter() painter.begin(printer) # calculate margin and width of printout font = QFont("times", 10) painter.setFont(font) fm = painter.fontMetrics() fontHeight = fm.lineSpacing() marginX = printer.pageRect().x() - printer.paperRect().x() marginX = Preferences.getPrinter("LeftMargin") * \ int(printer.resolution() / 2.54) - marginX marginY = printer.pageRect().y() - printer.paperRect().y() marginY = Preferences.getPrinter("TopMargin") * \ int(printer.resolution() / 2.54) - marginY width = printer.width() - marginX - \ Preferences.getPrinter("RightMargin") * \ int(printer.resolution() / 2.54) height = printer.height() - fontHeight - 4 - marginY - \ Preferences.getPrinter("BottomMargin") * \ int(printer.resolution() / 2.54) # write a foot note s = self.tr("Diagram: {0}").format(self.getDiagramName()) tc = QColor(50, 50, 50) painter.setPen(tc) painter.drawRect(marginX, marginY, width, height) painter.drawLine(marginX, marginY + height + 2, marginX + width, marginY + height + 2) painter.setFont(font) painter.drawText(marginX, marginY + height + 4, width, fontHeight, Qt.AlignRight, s) # render the diagram size = self.pixmapLabel.pixmap().size() size.scale(QSize(width - 10, height - 10), # 5 px inner margin Qt.KeepAspectRatio) painter.setViewport(marginX + 5, marginY + 5, size.width(), size.height()) painter.setWindow(self.pixmapLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.pixmapLabel.pixmap()) painter.end()
def paintEvent(self, evt): """ Protected method handling paint events. @param evt paint event (QPaintEvent) """ if self.__grabbing: # grabWindow() should just get the background return painter = QPainter(self) pal = QPalette(QToolTip.palette()) font = QToolTip.font() handleColor = pal.color(QPalette.Active, QPalette.Highlight) handleColor.setAlpha(160) overlayColor = QColor(0, 0, 0, 160) textColor = pal.color(QPalette.Active, QPalette.Text) textBackgroundColor = pal.color(QPalette.Active, QPalette.Base) painter.drawPixmap(0, 0, self.__pixmap) painter.setFont(font) pol = QPolygon(self.__selection) if not self.__selection.boundingRect().isNull(): # Draw outline around selection. # Important: the 1px-wide outline is *also* part of the # captured free-region pen = QPen(handleColor, 1, Qt.SolidLine, Qt.SquareCap, Qt.BevelJoin) painter.setPen(pen) painter.drawPolygon(pol) # Draw the grey area around the selection. grey = QRegion(self.rect()) grey = grey - QRegion(pol) painter.setClipRegion(grey) painter.setPen(Qt.NoPen) painter.setBrush(overlayColor) painter.drawRect(self.rect()) painter.setClipRect(self.rect()) drawPolygon(painter, pol, handleColor) if self.__showHelp: painter.setPen(textColor) painter.setBrush(textBackgroundColor) self.__helpTextRect = painter.boundingRect( self.rect().adjusted(2, 2, -2, -2), Qt.TextWordWrap, self.__helpText).translated(-self.__desktop.x(), -self.__desktop.y()) self.__helpTextRect.adjust(-2, -2, 4, 2) drawPolygon(painter, self.__helpTextRect, textColor, textBackgroundColor) painter.drawText(self.__helpTextRect.adjusted(3, 3, -3, -3), Qt.TextWordWrap, self.__helpText) if self.__selection.isEmpty(): return # The grabbed region is everything which is covered by the drawn # rectangles (border included). This means that there is no 0px # selection, since a 0px wide rectangle will always be drawn as a line. boundingRect = self.__selection.boundingRect() txt = "{0:n}, {1:n} ({2:n} x {3:n})".format(boundingRect.x(), boundingRect.y(), boundingRect.width(), boundingRect.height()) textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt) boundingRect = textRect.adjusted(-4, 0, 0, 0) polBoundingRect = pol.boundingRect() if (textRect.width() < polBoundingRect.width() - 2 * self.__handleSize) and \ (textRect.height() < polBoundingRect.height() - 2 * self.__handleSize) and \ polBoundingRect.width() > 100 and \ polBoundingRect.height() > 100: # center, unsuitable for small selections boundingRect.moveCenter(polBoundingRect.center()) textRect.moveCenter(polBoundingRect.center()) elif polBoundingRect.y() - 3 > textRect.height() and \ polBoundingRect.x() + textRect.width() < self.rect().width(): # on top, left aligned boundingRect.moveBottomLeft( QPoint(polBoundingRect.x(), polBoundingRect.y() - 3)) textRect.moveBottomLeft( QPoint(polBoundingRect.x() + 2, polBoundingRect.y() - 3)) elif polBoundingRect.x() - 3 > textRect.width(): # left, top aligned boundingRect.moveTopRight( QPoint(polBoundingRect.x() - 3, polBoundingRect.y())) textRect.moveTopRight( QPoint(polBoundingRect.x() - 5, polBoundingRect.y())) elif (polBoundingRect.bottom() + 3 + textRect.height() < self.rect().bottom()) and \ polBoundingRect.right() > textRect.width(): # at bottom, right aligned boundingRect.moveTopRight( QPoint(polBoundingRect.right(), polBoundingRect.bottom() + 3)) textRect.moveTopRight( QPoint(polBoundingRect.right() - 2, polBoundingRect.bottom() + 3)) elif polBoundingRect.right() + textRect.width() + 3 < \ self.rect().width(): # right, bottom aligned boundingRect.moveBottomLeft( QPoint(polBoundingRect.right() + 3, polBoundingRect.bottom())) textRect.moveBottomLeft( QPoint(polBoundingRect.right() + 5, polBoundingRect.bottom())) # If the above didn't catch it, you are running on a very # tiny screen... drawPolygon(painter, boundingRect, textColor, textBackgroundColor) painter.drawText(textRect, Qt.AlignHCenter, txt) if (polBoundingRect.height() > self.__handleSize * 2 and polBoundingRect.width() > self.__handleSize * 2) or \ not self.__mouseDown: painter.setBrush(Qt.transparent) painter.setClipRegion(QRegion(pol)) painter.drawPolygon(QPolygon(self.rect()))
def draw_game_over(self, qp: QPainter): qp.setFont(QFont('Segoe UI', 30)) qp.drawText(QtCore.QRect(0, 0, self.width, self.height), Qt.AlignCenter, 'GAME OVER')
class GameWidget(QWidget): """Виджет самой игры""" positionChanged = pyqtSignal(QPoint) def __init__(self, game_level, main_window, menu_widget): self.is_paused = False super().__init__() self.animation_manager = AnimationManager() self.ball_pixmap_provider = BallPixmapProvider() self.main_window = main_window self.menu_widget = menu_widget self.angle_provider = AngleProvider() self.game_level = game_level self.balls_float_animation = 0 self.pausa_opacity = 0 self.buttons = [ MenuButton(200, 400, "resources/kadilo.png", self.back), MenuButton(200, 600, "resources/zavarudo.png", self.pause) ] self.task_manager = TaskManager() self.x = 1 self.y = 1 self.is_meta_menud = False self.game_state = GameState(game_level, RandomColorManager(time.time())) self.game_state.set_animation_manager(self.animation_manager) self.grid = QGridLayout() self.canvas = QPixmap(800, 800) self.label = QLabel() self.label.setPixmap(self.canvas) tracker = MouseTracker(self.label) tracker.positionChanged.connect(self.on_position_changed) self.grid.addWidget(self.label) self.setLayout(self.grid) self.animation_manager.add_animation(TipAnimation()) self.timer = QTimer() self.timer.timeout.connect(self.handle_timer) self.timer.start(40) def pause(self): self.is_paused = not self.is_paused if self.is_paused: self.task_manager.add_task(UpPausaTask(self)) else: self.task_manager.add_task(DownPausaTask(self)) def draw_meta_menus(self): if self.is_meta_menud: self.draw_buttons() def change_meta_menud_state(self): self.is_meta_menud = not self.is_meta_menud def add_balls_float_parameter(self): self.balls_float_animation += 0.2 def handle_timer(self): self.task_manager.task_tick() if self.game_state.game_ended_win: self.end_game_win() if self.game_state.lost: self.end_game_lose() if not self.is_paused: self.add_balls_float_parameter() # visual effect self.game_state.tick() self.angle = self.angle_provider.get_angle(self.x, self.y) self.draw_game_state() def left_click(self): self.main_window.setFocus() self.game_state.shot_a_ball(self.angle) def set_pausa_opacity(self, pausa_opacity): self.pausa_opacity = pausa_opacity def right_click(self): self.game_state.swap_balls() def wheel_click(self): self.game_state.change_balls() def mousePressEvent(self, a0: QMouseEvent) -> None: if self.is_meta_menud: for i in self.buttons: if i.is_pressed: i.on_click() if a0.button() == 1: self.left_click() elif a0.button() == 2: self.right_click() elif a0.button() == 4: self.wheel_click() def draw_game_state(self): self.label.setPixmap(QPixmap(self.game_level.map_resource)) self.qp = QPainter(self.label.pixmap()) self.qp.setFont(QFont("arial", 22)) self.draw_central_frog() self.draw_conveyor_balls() self.draw_flying_balls() self.draw_score() self.animation_manager.draw_animations(self.qp) self.draw_meta_menus() self.draw_pausa() self.qp.end() self.update() def draw_buttons(self): for i in self.buttons: x, y, w, h = i.get_geometry() self.qp.drawPixmap(x, y, w, h, QPixmap(i.get_pixmap())) self.qp.drawPixmap(x, y, w, h, QPixmap(i.text_resource)) def draw_score(self): self.qp.setPen(QColor(0, 0, 0)) x, y = self.game_level.score_position self.qp.drawText(x, y, str(self.game_state.score)) def draw_flying_balls(self): bpp = self.ball_pixmap_provider for i in self.game_state.balls: if i.must_been_deleted: continue self.qp.drawPixmap(i.x - 21, i.y - 21, 42, 42, bpp.get_pixmap(i.color)) def draw_conveyor_balls(self): bpp = self.ball_pixmap_provider for i in self.game_state.balls_conveyor.get_balls_list(): x, y = self.game_state.balls_conveyor.get_ball_position(i) self.qp.drawPixmap(x - i.diameter / 2, y - i.diameter / 2, i.diameter, i.diameter, bpp.get_pixmap(i.color)) def draw_pausa(self): if not self.is_paused: return self.qp.setOpacity(self.pausa_opacity) self.qp.drawPixmap(150, 100, 312 * 1.5, 180 * 1.5, QPixmap("resources/pausa_png.png")) self.qp.setOpacity(1) def draw_central_frog(self): bpp = self.ball_pixmap_provider self.qp.setPen(QPen(QColor("black"), 3)) x, y = self.game_level.frog_position self.qp.drawPixmap(x - 35, y - 50, QPixmap("resources/frog.png")) p = self.game_state.frog_operator.balls_swap_parameter p2 = self.game_state.frog_operator.balls_swap_parameter2 p3 = 1 - self.game_state.frog_operator.balls_swap_parameter3 self.qp.drawPixmap( x + 40 * p, y - 60 * p, p3 * (42 - 21 * p), p3 * (42 - 21 * p), bpp.get_pixmap(self.game_state.frog_operator.first_ball_color)) self.qp.drawPixmap( x + 40 - 80 * p, y - 60 + 10 * math.sin(self.balls_float_animation), p3 * 21, p3 * 21, bpp.get_pixmap(self.game_state.frog_operator.second_ball_color)) self.qp.drawPixmap( x - 40 + 40 * p2, y - 60 + 60 * p2 + 10 * math.sin(self.balls_float_animation), p3 * (21 - 21 * p + 42 * p2), p3 * (21 - 21 * p + 42 * p2), bpp.get_pixmap(self.game_state.frog_operator.third_ball_color)) if self.game_state.frog_operator.change_balls_cooldown > 0: self.qp.drawText( x, y + 80, str( int(self.game_state.frog_operator.change_balls_cooldown / 25))) self.qp.drawLine(x + 15, y + 15, x + 15 + 100 * math.cos(self.angle), y + 15 + 100 * math.sin(self.angle)) def back(self): self.main_window.setCentralWidget(type(self.main_window)()) def end_game_win(self): self.main_window.setCentralWidget( EndGameWinWidget(self.main_window, self.menu_widget, self.game_state.score, self.game_level.number)) def end_game_lose(self): self.main_window.setCentralWidget( EndGameLoseWidget(self.main_window, self.menu_widget)) @pyqtSlot(QPoint) def on_position_changed(self, pos): for i in self.buttons: x, y, w, h = i.get_geometry() if x < pos.x() < x + w and y < pos.y() < y + h: i.is_pressed = True else: i.is_pressed = False self.x = pos.x() - 415 self.y = pos.y() - 415
def overlay_marks(self, img, is_cseed=False, calibration_sheet=False): border_color = Qt.white base_img = QImage(self.f_size.width(), self.f_size.height(), QImage.Format_ARGB32) base_img.fill(border_color) img = QImage(img) painter = QPainter() painter.begin(base_img) total_distance_h = round(base_img.width() / self.abstand_v) dist_v = round(total_distance_h) / 2 dist_h = round(total_distance_h) / 2 img = img.scaledToWidth(base_img.width() - (2 * (total_distance_h))) painter.drawImage(total_distance_h, total_distance_h, img) #frame around image pen = QPen(Qt.black, 2) painter.setPen(pen) #horz painter.drawLine(0, total_distance_h, base_img.width(), total_distance_h) painter.drawLine(0, base_img.height() - (total_distance_h), base_img.width(), base_img.height() - (total_distance_h)) #vert painter.drawLine(total_distance_h, 0, total_distance_h, base_img.height()) painter.drawLine(base_img.width() - (total_distance_h), 0, base_img.width() - (total_distance_h), base_img.height()) #border around img border_thick = 6 Rpath = QPainterPath() Rpath.addRect( QRectF((total_distance_h) + (border_thick / 2), (total_distance_h) + (border_thick / 2), base_img.width() - ((total_distance_h) * 2) - ((border_thick) - 1), (base_img.height() - ((total_distance_h)) * 2) - ((border_thick) - 1))) pen = QPen(Qt.black, border_thick) pen.setJoinStyle(Qt.MiterJoin) painter.setPen(pen) painter.drawPath(Rpath) Bpath = QPainterPath() Bpath.addRect( QRectF((total_distance_h), (total_distance_h), base_img.width() - ((total_distance_h) * 2), (base_img.height() - ((total_distance_h)) * 2))) pen = QPen(Qt.black, 1) painter.setPen(pen) painter.drawPath(Bpath) pen = QPen(Qt.black, 1) painter.setPen(pen) painter.drawLine(0, base_img.height() / 2, total_distance_h, base_img.height() / 2) painter.drawLine(base_img.width() / 2, 0, base_img.width() / 2, total_distance_h) painter.drawLine(base_img.width() - total_distance_h, base_img.height() / 2, base_img.width(), base_img.height() / 2) painter.drawLine(base_img.width() / 2, base_img.height(), base_img.width() / 2, base_img.height() - total_distance_h) #print code f_size = 37 QFontDatabase.addApplicationFont( os.path.join(os.path.dirname(__file__), 'DejaVuSansMono-Bold.ttf')) font = QFont("DejaVu Sans Mono", f_size - 11, QFont.Bold) font.setPixelSize(35) painter.setFont(font) if not calibration_sheet: if is_cseed: #its a secret painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) painter.drawImage( ((total_distance_h)) + 11, ((total_distance_h)) + 11, QImage(icon_path('electrumb.png')).scaledToWidth( 2.1 * (total_distance_h), Qt.SmoothTransformation)) painter.setPen(QPen(Qt.white, border_thick * 8)) painter.drawLine( base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2, base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2 - 77, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2) painter.setPen(QColor(0, 0, 0, 255)) painter.drawText( QRect( 0, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 11, base_img.height() - total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.version + '_' + self.versioned_seed.checksum) painter.end() else: # revealer painter.setPen(QPen(border_color, 17)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) painter.setPen(QPen(Qt.black, 2)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) logo = QImage(icon_path('revealer_c.png')).scaledToWidth( 1.3 * (total_distance_h)) painter.drawImage((total_distance_h) + (border_thick), ((total_distance_h)) + (border_thick), logo, Qt.SmoothTransformation) #frame around logo painter.setPen(QPen(Qt.black, border_thick)) painter.drawLine( total_distance_h + border_thick, total_distance_h + logo.height() + 3 * (border_thick / 2), total_distance_h + logo.width() + border_thick, total_distance_h + logo.height() + 3 * (border_thick / 2)) painter.drawLine( logo.width() + total_distance_h + 3 * (border_thick / 2), total_distance_h + (border_thick), total_distance_h + logo.width() + 3 * (border_thick / 2), total_distance_h + logo.height() + (border_thick)) #frame around code/qr qr_size = 179 painter.drawLine((base_img.width() - ((total_distance_h)) - (border_thick / 2) - 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2, (base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2) painter.drawLine( (base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2, base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2 - qr_size, ((base_img.height() - ((total_distance_h))) - (border_thick / 2) - 2)) painter.setPen(QPen(Qt.white, border_thick * 8)) painter.drawLine( base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2, base_img.width() / 2 + (total_distance_h / 2) - border_thick - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2) painter.setPen(QColor(0, 0, 0, 255)) painter.drawText( QRect(((base_img.width() / 2) + 21) - qr_size, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 93, base_img.height() - total_distance_h - border_thick), Qt.AlignLeft, self.versioned_seed.get_ui_string_version_plus_seed()) painter.drawText( QRect( 0, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 3 - qr_size, base_img.height() - total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.checksum) # draw qr code qr_qt = self.paintQR( self.versioned_seed.get_ui_string_version_plus_seed() + self.versioned_seed.checksum) target = QRectF(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, qr_size, qr_size) painter.drawImage(target, qr_qt) painter.setPen(QPen(Qt.black, 4)) painter.drawLine(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, base_img.width() - 65 - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 4) painter.drawLine(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, base_img.width() - 65, base_img.height() - 65 - qr_size) painter.end() else: # calibration only painter.end() cal_img = QImage(self.f_size.width() + 100, self.f_size.height() + 100, QImage.Format_ARGB32) cal_img.fill(Qt.white) cal_painter = QPainter() cal_painter.begin(cal_img) cal_painter.drawImage(0, 0, base_img) #black lines in the middle of border top left only cal_painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine)) cal_painter.drawLine(0, dist_v, base_img.width(), dist_v) cal_painter.drawLine(dist_h, 0, dist_h, base_img.height()) pen = QPen(Qt.black, 2, Qt.DashDotDotLine) cal_painter.setPen(pen) n = 15 cal_painter.setFont(QFont("DejaVu Sans Mono", 21, QFont.Bold)) for x in range(-n, n): #lines on bottom (vertical calibration) cal_painter.drawLine((((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) - 13, x + 2 + base_img.height() - (dist_v), (((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) + 13, x + 2 + base_img.height() - (dist_v)) num_pos = 9 if x > 9: num_pos = 17 if x < 0: num_pos = 20 if x < -9: num_pos = 27 cal_painter.drawText((((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) - num_pos, 50 + base_img.height() - (dist_v), str(x)) #lines on the right (horizontal calibrations) cal_painter.drawLine( x + 2 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / n) + (base_img.height() / 2) - 13, x + 2 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / n) + (base_img.height() / 2) + 13) cal_painter.drawText(30 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / 2) + 13, str(x)) cal_painter.end() base_img = cal_img return base_img
def draw_game_won(self, qp: QPainter): qp.setFont(QFont('Segoe UI', 30)) qp.drawText( QtCore.QRect(0, 0, self.width, self.height), Qt.AlignCenter, 'Congratulations,\n you won the game!\n' f'Your final score is {self.game.score}')
def paintEvent(self, e): ''' Подновляет (рисует) изображение памяти по-пиксельно ''' if self.startAddress == None: return qp = QPainter() qp.begin(self) # Подписываем адреса qp.setFont(QFont('DejaVu Sans Bold', 10, QFont.Bold)) rect = QRect(X0, 0, (dX * 7), dY) #qp.drawRect(rect) addr = ( (self.startAddress) >> 16) & 0xFFFF # Берём только цифры ZZZZ.... txt = "{:04X}".format(addr) qp.drawText(rect, (Qt.AlignVCenter | Qt.AlignHCenter), txt) qp.setFont(QFont('DejaVu Sans', 10)) for y in range(7): rect = QRect(0, (y * dY + Y0), X0, dY) #qp.drawRect(rect) addr = ((self.startAddress + y * 256) >> 8) & 0xFF # Берём только цифры ....YY.. txt = "{:02X}xx".format(addr) qp.drawText(rect, (Qt.AlignVCenter | Qt.AlignHCenter), txt) for x in range(7): rect = QRect((x * dX + X0), (Y0 - dY), dX, dY) #qp.drawRect(rect) addr = (self.startAddress + x) & 0xFF # Берём только цифры ......XX txt = "{:02X}".format(addr) qp.drawText(rect, (Qt.AlignVCenter | Qt.AlignHCenter), txt) #qp.setFont(QFont('DejaVu Sans', 10)) for y in range(7): for x in range(7): rect = QRect((x * dX + X0), (y * dY + Y0), (dX - 1), (dY - 1)) if self.content != None: c = self.content[y][x] r = (c >> 5) & 0x07 g = (c >> 2) & 0x07 b = (c) & 0x03 #qp.setPen(QPen(QColor(r, g, b))) color = QColor(r << 5, g << 5, b << 6) qp.fillRect(rect, color) qp.drawRect(rect) bright = r * 28 + g * 61 + b * 11 if bright < (656 / 2): qp.setPen(Qt.white) else: qp.setPen(Qt.black) txt = "{:02X}".format(self.content[y][x]) qp.drawText(rect, (Qt.AlignVCenter | Qt.AlignHCenter), txt) #qp.setFont(QFont('DejaVu Sans Bold', 10, QFont.Bold)) #qp.setPen(QColor("Blue")) # qp.drawText(rect, Qt.Alignment((Qt.AlignVCenter | Qt.AlignHCenter)), self.startAddress) #qp.setPen(QColor("Black")) qp.end()
def draw_pause(self, qp: QPainter): qp.setFont(QFont('Segoe UI', 30)) qp.drawText(QtCore.QRect(0, 0, self.width, self.height), Qt.AlignCenter, 'Paused')
def paintEvent(self, event): painter = QPainter() painter.begin(self) self.draw_map(painter) for tower in self.game.player.towers: matrix = painter.transform() painter.translate(tower.location.X, tower.location.Y) pic = self.images[tower.image][tower.level] painter.drawImage(-pic.width() / 2, -pic.height() / 2, pic) painter.setTransform(matrix) for enemy in self.game.monsters: matrix = painter.transform() painter.translate(enemy.location.X, enemy.location.Y) pic = self.images[enemy.image][enemy.get_image()]\ .mirrored(math.pi - enemy.dir < 0.025, False) painter.drawImage(-pic.width() / 2, -pic.height() / 2, pic) painter.fillRect(-pic.width() / 2, -pic.height() / 2 - 10, pic.width(), 7, self.red) painter.fillRect(-pic.width() / 2, -pic.height() / 2 - 10, pic.width() * enemy.heath_percents(), 7, self.green) painter.setTransform(matrix) for bullet in self.game.bullets: matrix = painter.transform() pic = self.images[bullet.image] angle = 90 + (bullet.direction * 180 / math.pi) painter.translate(bullet.location.X, bullet.location.Y) painter.rotate(angle) painter.drawImage(-pic.width() / 2, -pic.height() / 2, pic) painter.setTransform(matrix) painter.setFont(QFont('Decorative', 16)) painter.fillRect(20, 40, 250, 20, self.white) painter.fillRect(20, 40, 250 * self.game.player.mana / 100, 20, self.blue) painter.setPen(QColor(0, 0, 255)) painter.drawText(120, 58, 'Mana : {}'.format(self.game.player.mana)) painter.setPen(self.red) painter.drawText(10, 20, 'Health: {}'.format(self.game.player.health)) painter.setPen(QColor(255, 255, 0)) painter.drawText(120, 20, 'Gold: {}'.format(self.game.player.gold)) tower = self.game.tower if self.game.level < 2: painter.drawText(840, 50, str(self.prices['castle'][self.game.level]) + '$') painter.drawText(740, 50, self.prices['poison'] + '$') painter.drawText(640, 50, self.prices['magic'] + '$') painter.drawText(540, 50, self.prices['archers'] + '$') if self.game.tower is not None: painter.drawText(940, 50, str(tower.upg_price) + '$') pic = self.images[tower.image][tower.level] painter.setPen(self.green) painter.drawRect(tower.location.X - pic.width() / 2, tower.location.Y - pic.height() / 2, pic.width(), pic.height()) if self.game.spell is not None: if not self.game.spell.is_executed: pic = self.images[self.game.spell.image] painter.drawImage(0, 0, pic) self.game.spell.get_image() painter.end()
class Tetris(QWidget): screenWidth = None # 窗口宽度 screenHeight = None # 窗口高度 isGameStart = None # 游戏是否开始 isGameOver = None # 游戏是否结束 isPause = None # 游戏是否暂停 pauseButton = None # 暂停游戏按钮 resumeButton = None # 继续游戏按钮 restartButton = None # 重新开始游戏按钮 gameOverImage = None # 游戏结束时显示的图片 blockSize = None # 一个方块的大小(像素px) allRows = None # 所有的行 allColumns = None # 所有的列 allBlock = None # 二维数组, 记录方块 currentRow = None # 当前行 currentColumn = None # 当前列 dropTimer = None # 方块下降的定时器 updateTimer = None # 屏幕更新的定时器 removeBlockTimer = None # 消除方块的定时器 dropInterval = None # 方块下降定时器的时间间隔 updateInterval = None # 屏幕更新定时器的时间间隔 removeBlockInterval = None # 消除方块定时器的时间间隔 blocks = None # 枚举所有的方块 blockDict = None # 存储方块属性的字典 nextBlockDict = None # 存储下一个方块属性的字典 block = None # 当前的方块 shape = None # 当前方块的类型 index = None # 当前方块类型的下标 score = None # 得分情况 pixmap = None # 临时存储图片路径 paint = None # 画笔 font = None # 字体 def __init__(self, parent=None): super(Tetris, self).__init__(parent) self.screenWidth = 900 self.screenHeight = 800 self.setFocusPolicy(Qt.StrongFocus) # 设置焦点, 监听键盘 self.resize(self.screenWidth, self.screenHeight) self.initButton() self.initImage() def initButton(self): """初始化重新开始游戏的按钮""" # 暂停游戏按钮 self.pauseButton = QPushButton(self) self.pauseButton.setObjectName('pauseButton') self.pauseButton.setShortcut('P') self.pauseButton.setToolTip('暂停') # 悬停在按钮上的提示->暂停 self.pauseButton.move(self.screenWidth - 210, 5) # 按钮的位置 self.pauseButton.hide() # 默认隐藏 self.pauseButton.clicked.connect(lambda: { self.pause(), self.pauseButton.hide(), self.resumeButton.show(), }) # 继续游戏按钮 self.resumeButton = QPushButton(self) self.resumeButton.setObjectName('resumeButton') self.resumeButton.setToolTip('继续') # 悬停在按钮上的提示->继续 self.resumeButton.move(self.screenWidth - 210, 5) # 按钮的位置 self.resumeButton.hide() # 默认隐藏 self.resumeButton.clicked.connect(lambda: { self.resume(), self.resumeButton.hide(), self.pauseButton.show(), }) # 重新开始游戏按钮 self.restartButton = QPushButton(self) self.restartButton.setObjectName('restartButton') self.restartButton.move(self.screenWidth // 2 - 200, self.screenHeight // 2 - 50) self.restartButton.hide() # 默认隐藏 self.restartButton.clicked.connect(self.gameOver) def initImage(self): """初始化游戏结束的图片""" self.gameOverImage = QLabel(self) self.gameOverImage.setPixmap(QPixmap('./icons/game_over.png')) self.gameOverImage.move(self.screenWidth // 24, self.screenHeight // 4) self.gameOverImage.hide() # 默认隐藏 def initSetting(self): """初始化方块的一些初始值""" self.blocks = { 'L Shape': [[[0, 0], [0, -1], [0, -2], [1, -2]], [[-1, -1], [0, -1], [1, -1], [-1, -2]], [[-1, 0], [0, 0], [0, -1], [0, -2]], [[-1, -1], [0, -1], [1, -1], [1, 0]]], 'J Shape': [[[0, 0], [0, -1], [0, -2], [-1, -2]], [[-1, 0], [-1, -1], [0, -1], [1, -1]], [[0, 0], [1, 0], [0, -1], [0, -2]], [[-1, -1], [0, -1], [1, -1], [1, -2]]], 'Z Shape': [[[-1, 0], [0, 0], [0, -1], [1, -1]], [[0, 0], [0, -1], [-1, -1], [-1, -2]], [[-1, 0], [0, 0], [0, -1], [1, -1]], [[0, 0], [0, -1], [-1, -1], [-1, -2]]], 'S Shape': [[[-1, 0], [-1, -1], [0, -1], [0, -2]], [[0, 0], [1, 0], [-1, -1], [0, -1]], [[-1, 0], [-1, -1], [0, -1], [0, -2]], [[0, 0], [1, 0], [-1, -1], [0, -1]]], 'O Shape': [[[-1, 0], [0, 0], [-1, -1], [0, -1]], [[-1, 0], [0, 0], [-1, -1], [0, -1]], [[-1, 0], [0, 0], [-1, -1], [0, -1]], [[-1, 0], [0, 0], [-1, -1], [0, -1]]], 'I Shape': [[[0, 0], [0, -1], [0, -2], [0, -3]], [[-2, -1], [-1, -1], [0, -1], [1, -1]], [[0, 0], [0, -1], [0, -2], [0, -3]], [[-2, -1], [-1, -1], [0, -1], [1, -1]]], 'T Shape': [[[-1, -1], [0, -1], [1, -1], [0, -2]], [[0, 0], [-1, -1], [0, -1], [0, -2]], [[0, 0], [-1, -1], [0, -1], [1, -1]], [[0, 0], [0, -1], [1, -1], [0, -2]]] } self.score = 0 self.blockSize = 40 # 方块的大小 self.allRows = 20 # 总共20行 self.allColumns = 15 # 总共15列 self.currentRow = self.allRows + 4 # +4行是用来放置待出现的方块的 self.currentColumn = self.allColumns // 2 self.allBlock = [[0 for row in range(self.allColumns)] for column in range(self.allRows + 5)] self.allBlock[0] = [1 for column in range(self.allColumns)] # 用来判断方块是否到底 # print(self.allBlock) def initFont(self): """初始化字体""" # 使用本地字体 fontID = QFontDatabase.addApplicationFont('./Font/Consolas Italic.ttf') self.font = QFont() self.font.setFamily(QFontDatabase.applicationFontFamilies(fontID)[0]) self.font.setItalic(True) # 斜体 self.font.setBold(True) # 粗体 self.font.setPixelSize(40) # 字体大小 def initTimer(self): """初始化定时器""" # 方块下降的定时器 self.dropTimer = QTimer(self) self.dropInterval = 500 # 每0.5秒下降一格 self.dropTimer.start(self.dropInterval) self.dropTimer.timeout.connect(self.blockDrop) # paintEvent更新的定时器 self.updateTimer = QTimer(self) self.updateInterval = 10 self.updateTimer.start(self.updateInterval) self.updateTimer.timeout.connect(self.update) # 消除方块的定时器 self.removeBlockTimer = QTimer(self) self.removeBlockInterval = 150 self.removeBlockTimer.start(self.removeBlockInterval) self.removeBlockTimer.timeout.connect(self.removeBlock) def getBlock(self): """获取方块""" shape = random.choice(list(self.blocks.keys())) # 选择随机方块的类型 index = random.randint(0, 3) # if shape == 'L Shape' and index == 3: # pass block = self.blocks[shape][index] blockDict = { 'shape': shape, 'index': index, 'block': block, } return blockDict def getCurrentBlock(self): """获取目前的方块""" self.blockDict = self.nextBlockDict self.shape = self.blockDict['shape'] self.index = self.blockDict['index'] self.block = self.blockDict['block'] self.nextBlockDict = self.getBlock() def blockDrop(self): """每运行一次, 方块下降一格, 通过QTimer每隔一定时间运行一次""" for position1 in self.block: x = position1[0] + self.currentColumn # x->column y = position1[1] + self.currentRow # y->row # print(x, y) if self.allBlock[y - 1][x] == 1: for position2 in self.block: self.allBlock[position2[1] + self.currentRow][position2[0] + self.currentColumn] = 1 break else: # 下落方块没有接触到其他方块或者没有到底, 继续下降 self.currentRow -= 1 return # 判断游戏结束 if 1 in self.allBlock[self.allRows]: self.pause() self.update() self.removeBlockTimer.disconnect() self.updateTimer.disconnect() self.pauseButton.hide() self.gameOverImage.show() self.restartButton.show() return # 方块下落完成, 获取下一个方块 self.getCurrentBlock() self.currentRow = self.allRows + 4 self.currentColumn = self.allColumns // 2 def removeBlock(self): """消除方块""" # 叠满一行时消除方块, 从上往下消除 for row in range(self.allRows, 0, -1): if 0 not in self.allBlock[row]: # 消除方块时触发音效, 消除一行触发一次 player = QMediaPlayer(self) player.setMedia(QMediaContent(QUrl.fromLocalFile('./AudioFrequency/dingdong.mp3'))) player.play() self.allBlock.pop(row) # 即删即增 self.allBlock.append([0 for column in range(self.allColumns)]) self.score += 1 break def blockMove(self, movePosition): """左右移动方块movePosition>0 代表向右移动一格 <0 代表向左移动一格""" for position in self.block: x = position[0] + self.currentColumn + movePosition y = position[1] + self.currentRow if x < 0 or x > self.allColumns - 1 or y > self.allRows: # 说明方块左右移动出边界了 return elif self.allBlock[y][x] == 1: # 说明方块左右移动碰到方块了 return else: self.currentColumn += movePosition def rotate(self): """顺时针旋转方块""" for position in self.blocks[self.shape][(self.index + 1) % 4]: x = position[0] + self.currentColumn y = position[1] + self.currentRow # print(x, y) if x < 0 or x > self.allColumns - 1 or y > self.allRows: # 说明方块旋转时候出边界了 return elif self.allBlock[y][x] == 1: # 说明方块旋转时候碰到方块了 return else: self.index += 1 # print(self.blocks[self.shape][self.index % 4]) self.block = self.blocks[self.shape][self.index % 4] def start(self): """开始游戏""" self.isGameStart = True self.isGameOver = False self.isPause = False self.pauseButton.show() self.initSetting() self.initFont() self.initTimer() self.nextBlockDict = self.getBlock() self.getCurrentBlock() def pause(self): """游戏暂停""" self.isPause = True self.dropTimer.disconnect() def resume(self): """游戏继续""" self.isPause = False self.dropTimer.start(self.dropInterval) self.dropTimer.timeout.connect(self.blockDrop) def gameOver(self): """游戏结束""" self.isGameOver = True def paintEvent(self, event): """重写paintEvent, 使用QTimer, 每10ms调用一次""" self.paint = QPainter(self) self.paint.begin(self) # 开始重绘 if self.isGameStart is True: penColor = QColor(255, 255, 255) # 白色 # backgroundColor = QColor(255, 192, 203) # 粉色 self.paint.setPen(QPen(penColor, 2, Qt.SolidLine, Qt.RoundCap)) # 白色, self.pixmap = QPixmap('./icons/game_background.png') self.paint.drawPixmap(QRect(0, 0, self.screenWidth, self.screenHeight), self.pixmap) # 背景图片 self.paint.drawLine(self.screenWidth - 300, 0, self.screenWidth - 300, self.screenHeight) # 分割线 # 绘制正在下落的方块 for position in self.block: x = position[0] + self.currentColumn y = position[1] + self.currentRow self.paint.drawPixmap(QRect(x * self.blockSize, (self.allRows - y) * self.blockSize, self.blockSize, self.blockSize), QPixmap('./icons/block.png')) # 绘制静态方块 for row in range(1, self.allRows + 1): for column in range(self.allColumns): if self.allBlock[row][column] == 1: self.paint.drawPixmap(QRect(column * self.blockSize, (self.allRows - row) * self.blockSize, self.blockSize, self.blockSize), QPixmap('./icons/fill_block.png')) # 绘制下一个出现的方块 for position in self.nextBlockDict['block']: x = position[0] + 18.5 # 18.5是740px/40px(方块大小) y = position[1] + 12.5 # 7.5是500px/40px(方块大小) 从下往上 self.paint.drawPixmap(QRect(int(x * self.blockSize), int((self.allRows - y) * self.blockSize), self.blockSize, self.blockSize), QPixmap('./icons/block.png')) # 绘制得分情况 self.paint.setFont(self.font) self.paint.drawText(self.screenWidth - 250, 150, 'Score: %d' % self.score) self.paint.end() # 结束重绘 def keyPressEvent(self, event): """重写keyPressEvent""" if self.isGameOver is False and self.isPause is False: if event.key() == Qt.Key_A: self.blockMove(-1) elif event.key() == Qt.Key_D: self.blockMove(1) if event.key() == Qt.Key_W: self.rotate() if event.key() == Qt.Key_S: # 加速下降, 加速一个方格 self.blockDrop()
class MainWindow(QWidget): """Main window of the GUI containing the game board """ def __init__(self, game, area_text_fn=lambda area: str(area.get_dice())): """ Parameters ---------- game : Game """ self.logger = logging.getLogger('GUI') super(MainWindow, self).__init__() self.qp = QPainter() self.game = game self.board = game.board self.areas_mapping = {} for i, area in self.board.areas.items(): for h in area.get_hexes(): self.areas_mapping[h] = i self.font = QFont('Helvetica', 16) self.pen = QPen() self.pen.setWidth(2) self.activated_area_name = None self.area_text_fn = area_text_fn def paintEvent(self, event): self.qp.begin(self) self.draw_areas() self.qp.end() def set_area_text_fn(self, area_text_fn): self.area_text_fn = area_text_fn def draw_areas(self): """Draw areas in the game board """ if self.game.draw_battle: self.activated_area_name = None self.game.draw_battle = False size = self.size() x = size.width() y = size.height() bbox = hexutil.Rectangle(-x // 2, -y // 2, x, y) hexgrid = hexutil.HexGrid(10) self.qp.setPen(Qt.NoPen) self.qp.translate(x // 2, y // 2) for k, area in self.board.areas.items(): lines = [] first_hex = True color = player_color(area.get_owner_name()) if self.activated_area_name == int(k): color = (170 + color[0] // 3, 170 + color[1] // 3, 170 + color[2] // 3) self.qp.setBrush(QColor(*color)) self.qp.setPen(Qt.NoPen) for h in area.get_hexes(): polygon = QPolygon( [QPoint(*corner) for corner in hexgrid.corners(h)]) self.qp.drawPolygon(polygon) if first_hex: self.qp.save() rect = QRectF(*hexgrid.bounding_box(h)) self.qp.setBrush(QColor(0, 0, 0)) self.qp.setPen(self.pen) self.qp.setFont(self.font) self.qp.setRenderHint(QPainter.TextAntialiasing) self.qp.drawText(rect, Qt.AlignCenter, self.area_text_fn(area)) first_hex = False self.qp.restore() for n in h.neighbours(): if n not in area.get_hexes(): line = [] for corner in hexgrid.corners(h): if corner in hexgrid.corners(n): line.append(corner) lines.append(line) self.qp.save() pen = QPen() pen.setWidth(3) self.qp.setPen(pen) self.qp.setBrush(QColor()) self.qp.setRenderHint(QPainter.Antialiasing) for line in lines: self.qp.drawLine(line[0][0], line[0][1], line[1][0], line[1][1]) self.qp.restore() def mousePressEvent(self, event): hexagon = self.get_hex(event.pos()) try: area = self.board.get_area(self.areas_mapping[hexagon]) if self.activated_area_name: if area.get_name() == self.activated_area_name: self.activated_area_name = None self.update() elif (area.get_name() in self.activated_area.get_adjacent_areas() and area.get_owner_name() != self.game.current_player.get_name()): # attack self.game.send_message('battle', self.activated_area_name, area.get_name()) elif (area.get_owner_name() == self.game.player_name and self.game.player_name == self.game.current_player.get_name() and area.can_attack()): # area activation self.activated_area_name = area.get_name() self.activated_area = area self.update() except KeyError: pass def get_hex(self, position): """Return coordinates of a Hex from the given pixel position """ size = self.size() x = size.width() // 2 y = size.height() // 2 hexgrid = hexutil.HexGrid(10) return hexgrid.hex_at_coordinate(position.x() - x, position.y() - y)
def paintEvent(self, event): if self.is_speaking == True: return if self.is_start == False: self.is_start = True return painter = QPainter(self) current_point = self.gazeDataReceiver.current_point width = int(self.window_width / 3) height = int(self.window_height / 3) painter.setFont(self.font) for index in range(1, 10): x = int((index - 1) % 3) y = int((index - 1) / 3) # self.drawer.draw_normal_rectangle(painter, x, y, width, height) # 전체_영역_색칠 self.drawer.draw_normal_circle(painter, x, y, width, height) # 글자 표시 self.show_text(painter, x, y, width, height, index) if self.previous_point is None: self.previous_point = current_point return # start time 측정 if not self.is_checked: self.check_time() # 보고있는_포인트가_바뀌면_return elif self.previous_point != current_point: self.previous_point = current_point self.uncheck_time() return time_diff = round(time.time() - self.start_time, 2) ################# Main 카테고리 ################## # 3초동안 바라봐서 선택 했을경우. if time_diff > self.select_item_sec: # 카테고리 선택 if self.status == 0: # 비어있는 카테고리 선택 if (current_point > len(self.category_list)): print("카테고리 잘못선택!!") self.status = 0 self.uncheck_time() self.update() return print("카테고리 선택 : ", self.category_list[current_point - 1]) self.status = current_point self.uncheck_time() self.update() return #아이템 선택 elif self.status > 0: if current_point == 9: print("돌아가기") self.status = 0 self.uncheck_time() self.update() return if (current_point > len(self.item_list[self.status - 1])): print("비어있는 아이템") self.uncheck_time() self.update() return print("항목 선택 : ", self.item_list[self.status - 1][current_point - 1]) if self.debug_run_speak: self.is_speaking = True self.speak.speak_text(self.item_list[self.status - 1][current_point - 1]) self.is_speaking = False self.status = 0 self.uncheck_time() self.update() return # 3초세는_애니메이션 else: time_diff_rate = round(time_diff / self.select_item_sec, 2) x = int((current_point - 1) % 3) y = int((current_point - 1) / 3) # self.drawer.draw_growing_rectangle(painter, x, y, width, height, time_diff_rate) # 보고있는_포인트_표시 self.drawer.draw_growing_circle(painter, x, y, width, height, time_diff_rate) # 글자 표시 self.show_text(painter, x, y, width, height, current_point)
def paint(self, painter): painter.setRenderHint(QPainter.Antialiasing) pixelRatio = self.devicePixelRatioF() rect = QRectF(0, 0, self.width() * pixelRatio, self.height() * pixelRatio) sz = QSizeF(self.width() * pixelRatio, self.height() * pixelRatio).toSize() self.resizePixmap(sz) yOffset = rect.toRect().topLeft().y() + (100 - self.value() - 10) * sz.height() / 100 # draw water waterImage = QImage(sz, QImage.Format_ARGB32_Premultiplied) waterPainter = QPainter() waterPainter.begin(waterImage) waterPainter.setRenderHint(QPainter.Antialiasing) waterPainter.setCompositionMode(QPainter.CompositionMode_Source) pointStart = QPointF(sz.width() / 2, 0) pointEnd = QPointF(sz.width() / 2, sz.height()) linear = QLinearGradient(pointStart, pointEnd) startColor = QColor('#1F08FF') startColor.setAlphaF(1) endColor = QColor('#50FFF7') endColor.setAlphaF(0.28) linear.setColorAt(0, startColor) linear.setColorAt(1, endColor) linear.setSpread(QGradient.PadSpread) waterPainter.setPen(Qt.NoPen) waterPainter.setBrush(linear) waterPainter.drawEllipse(waterImage.rect().center(), sz.width() / 2 + 1, sz.height() / 2 + 1) waterPainter.setCompositionMode(QPainter.CompositionMode_SourceOver) waterPainter.drawImage(int(self.backXOffset), yOffset, self.waterBackImage) waterPainter.drawImage( int(self.backXOffset) - self.waterBackImage.width(), yOffset, self.waterBackImage) waterPainter.drawImage(int(self.frontXOffset), yOffset, self.waterFrontImage) waterPainter.drawImage( int(self.frontXOffset) - self.waterFrontImage.width(), yOffset, self.waterFrontImage) # draw pop if self.value() > 30: for pop in self.pops: popPath = QPainterPath() popPath.addEllipse(pop.xOffset * sz.width() / 100, (100 - pop.yOffset) * sz.height() / 100, pop.size * sz.width() / 100, pop.size * sz.height() / 100) waterPainter.fillPath(popPath, QColor(255, 255, 255, 255 * 0.3)) if self.isTextVisible(): font = waterPainter.font() rectValue = QRect() progressText = self.text().strip('%') if progressText == '100': font.setPixelSize(sz.height() * 35 / 100) waterPainter.setFont(font) rectValue.setWidth(sz.width() * 60 / 100) rectValue.setHeight(sz.height() * 35 / 100) rectValue.moveCenter(rect.center().toPoint()) waterPainter.setPen(Qt.white) waterPainter.drawText(rectValue, Qt.AlignCenter, progressText) else: font.setPixelSize(sz.height() * 40 / 100) waterPainter.setFont(font) rectValue.setWidth(sz.width() * 45 / 100) rectValue.setHeight(sz.height() * 40 / 100) rectValue.moveCenter(rect.center().toPoint()) rectValue.moveLeft(rect.left() + rect.width() * 0.45 * 0.5) waterPainter.setPen(Qt.white) waterPainter.drawText(rectValue, Qt.AlignCenter, progressText) font.setPixelSize(font.pixelSize() / 2) waterPainter.setFont(font) rectPerent = QRect( QPoint(rectValue.right(), rectValue.bottom() - rect.height() * 20 / 100), QPoint(rectValue.right() + rect.width() * 20 / 100, rectValue.bottom())) waterPainter.drawText(rectPerent, Qt.AlignCenter, '%') waterPainter.end() maskPixmap = QPixmap(sz) maskPixmap.fill(Qt.transparent) path = QPainterPath() path.addEllipse(QRectF(0, 0, sz.width(), sz.height())) maskPainter = QPainter() maskPainter.begin(maskPixmap) maskPainter.setRenderHint(QPainter.Antialiasing) maskPainter.setPen(QPen(Qt.white, 1)) maskPainter.fillPath(path, QBrush(Qt.white)) maskPainter.end() mode = QPainter.CompositionMode_SourceIn contentImage = QImage(sz, QImage.Format_ARGB32_Premultiplied) contentPainter = QPainter() contentPainter.begin(contentImage) contentPainter.setCompositionMode(QPainter.CompositionMode_Source) contentPainter.fillRect(contentImage.rect(), Qt.transparent) contentPainter.setCompositionMode(QPainter.CompositionMode_SourceOver) contentPainter.drawImage(0, 0, maskPixmap.toImage()) contentPainter.setCompositionMode(mode) contentPainter.drawImage(0, 0, waterImage) contentPainter.setCompositionMode( QPainter.CompositionMode_DestinationOver) contentPainter.end() contentImage.setDevicePixelRatio(pixelRatio) painter.drawImage(self.rect(), contentImage)
def paintEvent(self, a0: QtGui.QPaintEvent) -> None: if self.reference_point is not None and not self.isHidden(): lat_double, lon_double, zoom = self.reference_point h = self.size().height() w = self.size().width() dx = int(w) dy = int(h) # dx = int(w) * self.native_zoom # dy = int(h) * self.native_zoom # native_zoom_offset_x = dx*(self.native_zoom-1) # native_zoom_offset_y = dy*(self.native_zoom-1) xmid, ymid = int(lat_double), int(lon_double) xmid_, ymid_ = lat_double, lon_double offset_x, offset_y = (xmid_ - xmid), (ymid_ - ymid) xmin, ymax = xmid - 1, ymid + 1 xmax, ymin = xmid + 1, ymid - 1 qp = QPainter() qp.begin(self) x, y = -dx + self.XShift, -dy + self.YShift x += (0.5 - offset_x) * dx y += (0.5 - offset_y) * dy # x -= native_zoom_offset_x # y -= native_zoom_offset_y x0 = x y0 = y self.reference_point = lat_double + self.XShift / dx, lon_double + self.YShift / dy, zoom self.XShift = 0 self.YShift = 0 # for n in [[0, 0]]: # if not os.path.isfile("tiles/{0}_{1}_{2}.png".format(zoom, xmid + n[0], ymid + n[1])): # self.getImageCluster(xmin, ymid, zoom) # break for xtile in range(xmin, xmax + 1): for ytile in range(ymin, ymax + 1): save_path = None if self.mapType == 0: try: save_path = UKBParams.hardDrive + "tiles/{0}_{1}_{2}.png".format( zoom, xtile, ytile) qp.drawPixmap(QRect(x, y, dx, dy), QPixmap(save_path)) except: print("tile not found:", save_path) y += dy else: try: tiffList = [] for root, dirs, files in os.walk( '/home/pi/ukb/tiffmaps'): for names in files: if names.startswith( "{0}_{1}_{2}.png".format( zoom, xtile, ytile)): tiffList.append( os.path.join(root, names)) a = tiffList[0].find("cog_har_") save_path = UKBParams.hardDrive + "tiffmaps/" + tiffList[ 0][a:] qp.drawPixmap(QRect(x, y, dx, dy), QPixmap(save_path)) except: print("tile not found:", save_path) y += dy y = y0 x += dx # add markers for name in self.markers.keys(): lat, lon, color, title, size, font = self.markers[name] if lat is not None and lon is not None: xtile, ytile = self.deg2double(lat, lon, zoom) if xmin <= xtile <= xmax + 1 and ymin <= ytile <= ymax + 1: x, y = xtile - xmin, ytile - ymin x, y = x0 + x * dx, y0 + y * dy qp.setBrush(QBrush(color, Qt.SolidPattern)) qp.drawEllipse(x - size / 2, y - size / 2, size, size) if not title == "": qp.setFont(QFont('Decorative', font)) qp.drawText(x - size / 2, y - 2 - size / 2, title), # if self.native_zoom > 1: # print(self.native_zoom) # qp.translate(int(dx/2), int(dy/2)) # qp.scale(self.native_zoom, self.native_zoom) qp.end()
def paintEvent(self, event): super().paintEvent(event) if self.img == []: return if ((self.ex != self.sx or self.ey != self.sy)): # rect = QRect(self.sx, self.sy, abs(self.ex - self.sx), abs(self.ey - self.sy)) painter = QPainter(self) if (self.mode == 1): painter.setPen( QPen(Qt.red, self.linewide * 2 + 1, Qt.SolidLine, Qt.FlatCap)) painter.setFont(QtGui.QFont("Roman times", 15)) painter.setOpacity(0.5) painter.drawLine(self.sx, self.sy, self.ex, self.ey) painter.drawText(self.sx, self.sy, "[" + str(self.sx) + "," + str(self.sy) + "]") painter.drawText(self.ex, self.ey, "[" + str(self.ex) + "," + str(self.ey) + "]") elif (self.mode == 2): painter.setPen(QPen(Qt.blue, 3, Qt.DotLine)) painter.setFont(QtGui.QFont("Roman times", 15)) painter.drawLine(self.sx, self.sy, self.ex, self.ey) # painter.drawText(self.sx, self.sy, "["+str(self.sx)+","+str(self.sy)+"]") # painter.drawText(self.ex, self.ey, "["+str(self.ex)+","+str(self.ey)+"]") #计算垂直线段起始坐标 Vx1 = round(self.sx + (self.ey - self.sy) * self.linelen / ((self.ey - self.sy)**2 + (self.sx - self.ex)**2)**0.5) Vy1 = round(self.sy - (self.ex - self.sx) * self.linelen / ((self.ey - self.sy)**2 + (self.sx - self.ex)**2)**0.5) Vx2 = round(self.sx - (self.ey - self.sy) * self.linelen / ((self.ey - self.sy)**2 + (self.sx - self.ex)**2)**0.5) Vy2 = round(self.sy + (self.ex - self.sx) * self.linelen / ((self.ey - self.sy)**2 + (self.sx - self.ex)**2)**0.5) # 绘制垂直线段 painter.setPen( QPen(Qt.red, self.linewide * 2 + 1, Qt.SolidLine, Qt.FlatCap)) painter.setOpacity(0.5) painter.drawLine(self.sx, self.sy, Vx1, Vy1) painter.drawLine(self.sx, self.sy, Vx2, Vy2) painter.drawText(Vx1, Vy1, "[" + str(Vx1) + "," + str(Vy1) + "]") painter.drawText(Vx2, Vy2, "[" + str(Vx2) + "," + str(Vy2) + "]") #绘制中央基准线段 painter.setPen(QPen(Qt.red, 1, Qt.SolidLine, Qt.FlatCap)) painter.setOpacity(1.0) painter.drawLine(self.sx, self.sy, Vx1, Vy1) painter.drawLine(self.sx, self.sy, Vx2, Vy2) self.Vx1 = Vx1 self.Vx2 = Vx2 self.Vy1 = Vy1 self.Vy2 = Vy2 if (self.mode == 3): rx, ry = countPosition2(self.sx, self.sy, self.ex, self.ey, self.img) painter.setPen(QPen(Qt.red, 1, Qt.SolidLine)) painter.setFont(QtGui.QFont("Roman times", 15)) # painter.drawLine(self.sx, self.sy, self.ex, self.ey) painter.drawText(self.sx, self.sy, "[" + str(self.sx) + "," + str(self.sy) + "]") painter.drawText(self.ex, self.ey, "[" + str(self.ex) + "," + str(self.ey) + "]") painter.setOpacity(0.1) # painter.setPen(QPen(Qt.red,self.linewide*2+1, Qt.SolidLine,Qt.FlatCap)) painter.setPen(QPen(Qt.red, 2, Qt.SolidLine, Qt.FlatCap)) for i in range(len(rx)): painter.drawPoint(round(rx[i]), round(ry[i])) painter.setOpacity(1.0) painter.setPen(QPen(Qt.red, 2, Qt.SolidLine)) for i in range(len(rx)): painter.drawPoint(round(rx[i]), round(ry[i]))
class MapDisplay(QWidget): zoom_signal = pyqtSignal() press_signal = pyqtSignal(int, int) move_signal = pyqtSignal() def __init__(self, filename, parent=None): super(MapDisplay, self).__init__(parent) print('Loading Data...') self.map = DataAnalysis.map(filename) print('Total {} nodes, {} ways.'.format(len(self.map.cross_list.nodes), len(self.map.ways))) self.size_x = 680 self.size_y = 830 self.show_path = False self.zoom = [0, 0] # 第一个代表鼠标滚动之前(过去状态),第二个代表鼠标滚动之后(当前状态) self.max_zoom = 50 self.zoom_ratio = 1.1 self.mouse = QPoint(0, 0) # 发生事件时鼠标在屏幕上的位置(相对窗口左上角) self.top_left = node('5', lat_min, lon_min) # 图片左上角坐标 self.top_left.cartesian_coordinate(self.map.cross_list.origin) self.is_zoom = 0 # 缩放事件标记 self.is_press = 0 # 鼠标按下事件标记 self.before_drag = QPoint(0, 0) self.road_list = None self.min_distance = None self.intro = "" self.initUI() def initUI(self): self.setWindowTitle("At Tsinghua") self.setFixedWidth(self.size_x) self.setFixedHeight(self.size_y) self.painter = QPainter() self.show() def map_render(self): max_x = self.map.cross_list.farthest_node.x max_y = self.map.cross_list.farthest_node.y self.painter.setPen(Qt.NoPen) for wy in self.map.ways: attrs = wy.attr try: x = attrs['amenity'] except KeyError: continue if x == 'parking': self.painter.setBrush(QColor(254, 194, 146)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['surface'] if not x: continue except KeyError: continue if x == 'paving_stones' or x == 'paved' or x == 'concrete:plates' or x == 'asphalt' or x == 'cobblestone': self.painter.setBrush(QColor(220, 220, 220)) elif x == 'earth' or x == 'sand': self.painter.setBrush((QColor(231, 179, 22))) elif x == 'grass': self.painter.setBrush(QColor(55, 232, 30)) else: print('{} is not showed in surface'.format(x)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['leisure'] except KeyError: continue if x == 'swimming_pool': self.painter.setBrush(QColor(150, 182, 218)) elif x == 'park' or x == 'playground': self.painter.setBrush(QColor(150, 218, 179)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['natural'] except KeyError: continue if x == 'water': self.painter.setBrush(QColor(146, 160, 209)) elif x == 'grassland': self.painter.setBrush(QColor(55, 232, 30)) elif x == 'wood': self.painter.setBrush(QColor(75, 189, 72)) else: print('{} is not showed in natural'.format(x)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['landuse'] if not x: continue except KeyError: continue if x == 'grass' or x == 'meadow': self.painter.setBrush(QColor(55, 232, 30)) elif x == 'forest': self.painter.setBrush(QColor(75, 189, 72)) elif x == 'commercial' or x == 'retail' or x == 'construction' or x == 'park' or x == 'residential': self.painter.setBrush((QColor(220, 220, 220))) else: print('{} is not showed in landuse'.format(x)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['building'] if not x: continue except KeyError: continue self.painter.setBrush(QColor(213, 191, 223)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['waterway'] except KeyError: continue pen = QPen() pen.setColor(QColor(146, 160, 209)) pen.setWidth(8 * pow(self.zoom_ratio, 0.5 * self.zoom[1])) self.painter.setPen(pen) length = len(wy.point) - 1 for i in range(length): start = self.map.cross_list.get_node(wy.point[i]['ref']) end = self.map.cross_list.get_node(wy.point[i + 1]['ref']) self.painter.drawLine( start.x * self.size_x / max_x, self.size_y - start.y * self.size_y / max_y, end.x * self.size_x / max_x, self.size_y - end.y * self.size_y / max_y) for wy in self.map.ways: attrs = wy.attr try: x = attrs['highway'] if not x: continue except KeyError: continue pen = QPen() pen.setColor(QColor(202, 200, 153)) pen.setWidth(2 * pow(self.zoom_ratio, 0.5 * self.zoom[1])) self.painter.setPen(pen) length = len(wy.point) - 1 for i in range(length): start = self.map.cross_list.get_node(wy.point[i]['ref']) end = self.map.cross_list.get_node(wy.point[i + 1]['ref']) self.painter.drawLine( start.x * self.size_x / max_x, self.size_y - start.y * self.size_y / max_y, end.x * self.size_x / max_x, self.size_y - end.y * self.size_y / max_y) def paintEvent(self, e): self.painter.begin(self) rect = QRect(0, 0, 1000, 1000) self.painter.fillRect(rect, QColor(244, 241, 219)) self.map_render() self.mark() self.showPath() self.painter.end() # 鼠标滚轮事件 def wheelEvent(self, event): factor = 1.0 x = event.pos().x() y = event.pos().y() self.zoom[0] = self.zoom[1] d = event.angleDelta().y() if (self.zoom[1] + d / 120.0) >= 0 and (self.zoom[1] + d / 120.0) <= self.max_zoom: factor = pow(self.zoom_ratio, d / 240.0) self.zoom[1] = self.zoom[1] + d / 120.0 elif (self.zoom[1] + d / 120.0) > self.max_zoom: factor = pow(self.zoom_ratio, (self.max_zoom - self.zoom[1]) / 2) self.zoom[1] = self.max_zoom else: factor = pow(self.zoom_ratio, -self.zoom[1] / 2) self.zoom[1] = 0 mouse_lon = x / self.size_x * ( self.map.cross_list.farthest_node.lon - self.map.cross_list.origin.lon) + self.map.cross_list.origin.lon mouse_lat = self.map.cross_list.farthest_node.lat - y / self.size_y * ( self.map.cross_list.farthest_node.lat - self.map.cross_list.origin.lat) new_origin_lon = mouse_lon - (lon_max - lon_min) / ( self.size_x / x * pow(self.zoom_ratio, 0.5 * self.zoom[1])) if new_origin_lon <= lon_min: new_origin_lon = lon_min elif new_origin_lon > lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lon = lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) new_origin_lat = mouse_lat - (lat_max - lat_min) / ( self.size_y / (self.size_y - y) * pow(self.zoom_ratio, 0.5 * self.zoom[1])) if new_origin_lat <= lat_min: new_origin_lat = lat_min elif new_origin_lat > lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lat = lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) self.map.cross_list.origin.lon = new_origin_lon self.map.cross_list.origin.lat = new_origin_lat new_farthest_lon = new_origin_lon + (lon_max - lon_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) new_farthest_lat = new_origin_lat + (lat_max - lat_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) self.map.cross_list.farthest_node.lon = new_farthest_lon self.map.cross_list.farthest_node.lat = new_farthest_lat self.map.cross_list.farthest_node.cartesian_coordinate( self.map.cross_list.origin) self.map.cross_list.cartesian_coordinate() self.update() self.zoom_signal.emit() # 鼠标拖拽事件 def mousePressEvent(self, event): self.is_press = 1 x = event.pos().x() y = event.pos().y() self.before_drag = QPoint(x, y) self.max_lon_fixed = self.map.cross_list.farthest_node.lon self.min_lon_fixed = self.map.cross_list.origin.lon self.max_lat_fixed = self.map.cross_list.farthest_node.lat self.min_lat_fixed = self.map.cross_list.origin.lat self.press_signal.emit(int(x), int(y)) self.showIntro(x, y) def mouseReleaseEvent(self, event): self.is_press = 0 def mouseDoubleClickEvent(self, event): self.intro = "" self.update() def mouseMoveEvent(self, event): if self.is_press == 1: x = event.pos().x() y = event.pos().y() self.mouse = QPoint(x, y) new_origin_lon = (self.before_drag.x() - self.mouse.x()) * ( self.max_lon_fixed - self.min_lon_fixed) / self.size_x + self.min_lon_fixed if new_origin_lon <= lon_min: new_origin_lon = lon_min elif new_origin_lon > lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lon = lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) new_origin_lat = (self.mouse.y() - self.before_drag.y()) * ( self.max_lat_fixed - self.min_lat_fixed) / self.size_y + self.min_lat_fixed if new_origin_lat <= lat_min: new_origin_lat = lat_min elif new_origin_lat > lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lat = lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) self.map.cross_list.origin.lon = new_origin_lon self.map.cross_list.origin.lat = new_origin_lat new_farthest_lon = new_origin_lon + (lon_max - lon_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) new_farthest_lat = new_origin_lat + (lat_max - lat_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) self.map.cross_list.farthest_node.lon = new_farthest_lon self.map.cross_list.farthest_node.lat = new_farthest_lat self.map.cross_list.farthest_node.cartesian_coordinate( self.map.cross_list.origin) self.map.cross_list.cartesian_coordinate() self.update() self.move_signal.emit() # 坐标变换函数 def convertScreenToCoordinates(self, x, y): mouse_lon = x / self.size_x * ( self.map.cross_list.farthest_node.lon - self.map.cross_list.origin.lon) + self.map.cross_list.origin.lon mouse_lat = self.map.cross_list.farthest_node.lat - y / self.size_y * ( self.map.cross_list.farthest_node.lat - self.map.cross_list.origin.lat) return [mouse_lon, mouse_lat] def convertCoordinatesToScreen(self, lon, lat): x = (lon - self.map.cross_list.origin.lon) / ( self.map.cross_list.farthest_node.lon - self.map.cross_list.origin.lon) * self.size_x y = (self.map.cross_list.farthest_node.lat - lat) / (self.map.cross_list.farthest_node.lat - self.map.cross_list.origin.lat) * self.size_y return [x, y] # 放大函数 def zoomIn(self, x=-1.0, y=-1.0): if x < 0 or y < 0: x = self.size_x / 2 y = self.size_y / 2 self.mouse = QPoint(x, y) self.is_zoom = 1 self.zoom[0] = self.zoom[1] if self.zoom[1] < self.max_zoom: self.zoom[1] = self.zoom[1] + 1 factor = pow(self.zoom_ratio, 0.5) mouse_lon = x / self.size_x * ( self.map.cross_list.farthest_node.lon - self.map.cross_list. origin.lon) + self.map.cross_list.origin.lon mouse_lat = self.map.cross_list.farthest_node.lat - y / self.size_y * ( self.map.cross_list.farthest_node.lat - self.map.cross_list.origin.lat) new_origin_lon = mouse_lon - (lon_max - lon_min) / ( self.size_x / x * pow(self.zoom_ratio, 0.5 * self.zoom[1])) if new_origin_lon <= lon_min: new_origin_lon = lon_min elif new_origin_lon > lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lon = lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) new_origin_lat = mouse_lat - (lat_max - lat_min) / ( self.size_y / (self.size_y - y) * pow(self.zoom_ratio, 0.5 * self.zoom[1])) if new_origin_lat <= lat_min: new_origin_lat = lat_min elif new_origin_lat > lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lat = lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) self.map.cross_list.origin.lon = new_origin_lon self.map.cross_list.origin.lat = new_origin_lat new_farthest_lon = new_origin_lon + (lon_max - lon_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) new_farthest_lat = new_origin_lat + (lat_max - lat_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) self.map.cross_list.farthest_node.lon = new_farthest_lon self.map.cross_list.farthest_node.lat = new_farthest_lat self.map.cross_list.farthest_node.cartesian_coordinate( self.map.cross_list.origin) self.map.cross_list.cartesian_coordinate() self.update() self.zoom_signal.emit() # 缩小函数 def zoomOut(self, x=-1.0, y=-1.0): if x < 0 or y < 0: x = self.size_x / 2 y = self.size_y / 2 self.is_zoom = 1 self.zoom[0] = self.zoom[1] if self.zoom[1] > 0: self.zoom[1] = self.zoom[1] - 1 factor = pow(self.zoom_ratio, -0.5) mouse_lon = x / self.size_x * ( self.map.cross_list.farthest_node.lon - self.map.cross_list. origin.lon) + self.map.cross_list.origin.lon mouse_lat = self.map.cross_list.farthest_node.lat - y / self.size_y * ( self.map.cross_list.farthest_node.lat - self.map.cross_list.origin.lat) new_origin_lon = mouse_lon - (lon_max - lon_min) / ( self.size_x / x * pow(self.zoom_ratio, 0.5 * self.zoom[1])) if new_origin_lon <= lon_min: new_origin_lon = lon_min elif new_origin_lon > lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lon = lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) new_origin_lat = mouse_lat - (lat_max - lat_min) / ( self.size_y / (self.size_y - y) * pow(self.zoom_ratio, 0.5 * self.zoom[1])) if new_origin_lat <= lat_min: new_origin_lat = lat_min elif new_origin_lat > lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lat = lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) self.map.cross_list.origin.lon = new_origin_lon self.map.cross_list.origin.lat = new_origin_lat new_farthest_lon = new_origin_lon + (lon_max - lon_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) new_farthest_lat = new_origin_lat + (lat_max - lat_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) self.map.cross_list.farthest_node.lon = new_farthest_lon self.map.cross_list.farthest_node.lat = new_farthest_lat self.map.cross_list.farthest_node.cartesian_coordinate( self.map.cross_list.origin) self.map.cross_list.cartesian_coordinate() self.update() self.zoom_signal.emit() # 移动函数 def Move(self, delta_x, delta_y): self.max_lon_fixed = self.map.cross_list.farthest_node.lon self.min_lon_fixed = self.map.cross_list.origin.lon self.max_lat_fixed = self.map.cross_list.farthest_node.lat self.min_lat_fixed = self.map.cross_list.origin.lat new_origin_lon = (-delta_x) * (self.max_lon_fixed - self.min_lon_fixed ) / self.size_x + self.min_lon_fixed if new_origin_lon <= lon_min: new_origin_lon = lon_min elif new_origin_lon > lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lon = lon_max - (lon_max - lon_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) new_origin_lat = (delta_y) * (self.max_lat_fixed - self.min_lat_fixed ) / self.size_y + self.min_lat_fixed if new_origin_lat <= lat_min: new_origin_lat = lat_min elif new_origin_lat > lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]): new_origin_lat = lat_max - (lat_max - lat_min) * pow( self.zoom_ratio, -0.5 * self.zoom[1]) self.map.cross_list.origin.lon = new_origin_lon self.map.cross_list.origin.lat = new_origin_lat new_farthest_lon = new_origin_lon + (lon_max - lon_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) new_farthest_lat = new_origin_lat + (lat_max - lat_min) / pow( self.zoom_ratio, 0.5 * self.zoom[1]) self.map.cross_list.farthest_node.lon = new_farthest_lon self.map.cross_list.farthest_node.lat = new_farthest_lat self.map.cross_list.farthest_node.cartesian_coordinate( self.map.cross_list.origin) self.map.cross_list.cartesian_coordinate() self.update() self.move_signal.emit() # 显示区域左上角在原图中坐标 def displayTopLeft(self): x = -self.top_left.x y = -self.top_left.y return QPoint(x, y) # 显示区域右下角在原图中坐标 def displayBottomRight(self): x = self.size_x / pow(self.zoom_ratio, 0.5 * self.zoom[1]) - self.top_left.x y = self.size_y / pow(self.zoom_ratio, 0.5 * self.zoom[1]) - self.top_left.y return QPoint(x, y) # 缩放比例 def zoomRatio(self): return pow(self.zoom_ratio, 0.5 * self.zoom[1]) def mark(self): for wy in self.map.ways: try: name = wy.attr['name'] try: x = wy.attr['highway'] continue except KeyError: pass try: x = wy.attr['waterway'] continue except KeyError: pass rect = self.map.way_rect(wy) #l = rect[2] * pow(self.zoom_ratio, 0.5 * self.zoom[1] + 1) / (len(name)) l = 10 * get_dpi_rate() if name == "篮球场": rect = (rect[0], rect[1], rect[2] / 2, rect[3]) if (l / get_dpi_rate()) > rect[2] * pow( self.zoom_ratio, 0.5 * self.zoom[1] + 1) / (len(name)) or rect[3] * pow( self.zoom_ratio, 0.5 * self.zoom[1] + 1) < l: continue height = self.map.cross_list.farthest_node.y weight = self.map.cross_list.farthest_node.x self.painter.setFont(QFont('Microsoft Yahei', l, 75)) self.painter.setPen(QColor(150, 150, 150)) self.painter.drawText( rect[0] / weight * self.size_x - 1, \ self.size_y - (rect[1] + rect[3]) / height * self.size_y + 1, \ rect[2] / weight * self.size_x, \ rect[3] / height * self.size_y, \ Qt.AlignCenter, \ name) self.painter.setPen(QColor(0, 0, 0)) self.painter.drawText( rect[0] / weight * self.size_x, \ self.size_y - (rect[1] + rect[3]) / height * self.size_y, \ rect[2] / weight * self.size_x, \ rect[3] / height * self.size_y, \ Qt.AlignCenter, \ name) except KeyError: continue self.painter.setFont(QFont('Microsoft Yahei', 14 * get_dpi_rate(), 75)) self.painter.setPen(QColor(255, 255, 255)) self.painter.drawPixmap( QRect(0, 800, 680, 30), QPixmap("../data/icons/Caption_Background.png"), QRect(0, 0, 680, 30)) self.painter.drawText(10, 800, 660, 30, Qt.AlignLeft, self.intro) def getPath(self, road_list, min_distance): self.road_list = road_list self.min_distance = min_distance def showPath(self): if self.show_path: pen = QPen() pen.setColor(QColor(255, 0, 0)) pen.setWidth(5) self.painter.setPen(pen) test_list_length = len(self.road_list) - 1 for i in range(test_list_length): start = self.convertCoordinatesToScreen( self.road_list[i].lon, self.road_list[i].lat) end = self.convertCoordinatesToScreen( self.road_list[i + 1].lon, self.road_list[i + 1].lat) self.painter.drawLine(start[0], start[1], end[0], end[1]) def showIntro(self, x, y): if x == 0 and y == 0: return None width = self.map.cross_list.farthest_node.x - self.map.cross_list.origin.x height = self.map.cross_list.farthest_node.y - self.map.cross_list.origin.y x = x / self.size_x * width y = (self.size_y - y) / self.size_y * height for wy in self.map.ways: try: a = wy.attr['introduction'] except KeyError: continue try: a = wy.attr['highway'] continue except KeyError: pass nCross = 0 length = len(wy.point) - 1 for i in range(length): pt1 = self.map.cross_list.get_node(wy.point[i]['ref']) pt2 = self.map.cross_list.get_node(wy.point[i + 1]['ref']) if pt1.y == pt2.y or y < min([pt1.y, pt2.y]) or y > max( [pt1.y, pt2.y]): continue nx = (y - pt1.y) * (pt2.x - pt1.x) / (pt2.y - pt1.y) + pt1.x if nx > x: nCross += 1 if nCross % 2 == 1: self.intro = wy.attr['introduction'] self.update()
def paintEvent(self, event): painter = QPainter(self) event.accept() painter.save() painter.setRenderHint(QPainter.Antialiasing, True) if self.fLabel: if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_NULL: painter.setPen(self.fLabelGradientColor2) painter.setBrush(self.fLabelGradient) painter.drawRect(self.fLabelGradientRect) painter.setFont(self.fLabelFont) painter.setPen( self.fLabelGradientColorT[0 if self.isEnabled() else 1]) painter.drawText(self.fLabelPos, self.fLabel) if self.isEnabled(): normValue = float(self.fRealValue - self.fMinimum) / float(self.fMaximum - self.fMinimum) target = QRectF(0.0, 0.0, self.fPixmapBaseSize, self.fPixmapBaseSize) curLayer = int((self.fPixmapLayersCount - 1) * normValue) if self.fPixmapOrientation == self.HORIZONTAL: xpos = self.fPixmapBaseSize * curLayer ypos = 0.0 else: xpos = 0.0 ypos = self.fPixmapBaseSize * curLayer source = QRectF(xpos, ypos, self.fPixmapBaseSize, self.fPixmapBaseSize) painter.drawPixmap(target, self.fPixmap, source) # Custom knobs (Dry/Wet and Volume) if self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_WET, self.CUSTOM_PAINT_MODE_CARLA_VOL): # knob color colorGreen = QColor(0x5D, 0xE7, 0x3D).lighter(100 + self.fHoverStep * 6) colorBlue = QColor(0x3E, 0xB8, 0xBE).lighter(100 + self.fHoverStep * 6) # draw small circle ballRect = QRectF(8.0, 8.0, 15.0, 15.0) ballPath = QPainterPath() ballPath.addEllipse(ballRect) #painter.drawRect(ballRect) tmpValue = (0.375 + 0.75 * normValue) ballValue = tmpValue - floor(tmpValue) ballPoint = ballPath.pointAtPercent(ballValue) # draw arc startAngle = 216 * 16 spanAngle = -252 * 16 * normValue if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_WET: painter.setBrush(colorBlue) painter.setPen(QPen(colorBlue, 0)) painter.drawEllipse( QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2)) gradient = QConicalGradient(15.5, 15.5, -45) gradient.setColorAt(0.0, colorBlue) gradient.setColorAt(0.125, colorBlue) gradient.setColorAt(0.625, colorGreen) gradient.setColorAt(0.75, colorGreen) gradient.setColorAt(0.76, colorGreen) gradient.setColorAt(1.0, colorGreen) painter.setBrush(gradient) painter.setPen(QPen(gradient, 3)) else: painter.setBrush(colorBlue) painter.setPen(QPen(colorBlue, 0)) painter.drawEllipse( QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2)) painter.setBrush(colorBlue) painter.setPen(QPen(colorBlue, 3)) painter.drawArc(4.0, 4.0, 26.0, 26.0, startAngle, spanAngle) # Custom knobs (L and R) elif self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_L, self.CUSTOM_PAINT_MODE_CARLA_R): # knob color color = QColor(0xAD, 0xD5, 0x48).lighter(100 + self.fHoverStep * 6) # draw small circle ballRect = QRectF(7.0, 8.0, 11.0, 12.0) ballPath = QPainterPath() ballPath.addEllipse(ballRect) #painter.drawRect(ballRect) tmpValue = (0.375 + 0.75 * normValue) ballValue = tmpValue - floor(tmpValue) ballPoint = ballPath.pointAtPercent(ballValue) painter.setBrush(color) painter.setPen(QPen(color, 0)) painter.drawEllipse( QRectF(ballPoint.x(), ballPoint.y(), 2.0, 2.0)) # draw arc if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_L: startAngle = 216 * 16 spanAngle = -252.0 * 16 * normValue else: startAngle = 324.0 * 16 spanAngle = 252.0 * 16 * (1.0 - normValue) painter.setPen(QPen(color, 2)) painter.drawArc(3.5, 4.5, 22.0, 22.0, startAngle, spanAngle) # Custom knobs (Color) elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_COLOR: # knob color color = self.fCustomPaintColor.lighter(100 + self.fHoverStep * 6) # draw small circle ballRect = QRectF(8.0, 8.0, 15.0, 15.0) ballPath = QPainterPath() ballPath.addEllipse(ballRect) tmpValue = (0.375 + 0.75 * normValue) ballValue = tmpValue - floor(tmpValue) ballPoint = ballPath.pointAtPercent(ballValue) # draw arc startAngle = 216 * 16 spanAngle = -252 * 16 * normValue painter.setBrush(color) painter.setPen(QPen(color, 0)) painter.drawEllipse( QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2)) painter.setBrush(color) painter.setPen(QPen(color, 3)) painter.drawArc(4.0, 4.0, 26.0, 26.0, startAngle, spanAngle) # Custom knobs (Zita) elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_ZITA: a = normValue * pi * 1.5 - 2.35 r = 10.0 x = 10.5 y = 10.5 x += r * sin(a) y -= r * cos(a) painter.setBrush(Qt.black) painter.setPen(QPen(Qt.black, 2)) painter.drawLine(QPointF(11.0, 11.0), QPointF(x, y)) # Custom knobs else: painter.restore() return if self.HOVER_MIN < self.fHoverStep < self.HOVER_MAX: self.fHoverStep += 1 if self.fIsHovered else -1 QTimer.singleShot(20, self.update) else: # isEnabled() target = QRectF(0.0, 0.0, self.fPixmapBaseSize, self.fPixmapBaseSize) painter.drawPixmap(target, self.fPixmap, target) painter.restore()
class Battle(QWidget): """Widget for displaying battle results """ def __init__(self, game): super(Battle, self).__init__() self.game = game self.color = QColor(0, 0, 0) self.qp = QPainter() self.font = QFont('Helvetica', 12) self.pen = QPen() self.pen.setWidth(2) def paintEvent(self, event): self.qp.begin(self) self.draw_battle(event) self.qp.end() def draw_battle(self, event): """Draw battle results """ rect = event.rect() label_rect = QRectF(rect.x(), rect.y(), rect.width(), 25) self.qp.setPen(self.color) self.qp.setFont(self.font) self.qp.drawText(label_rect, Qt.AlignCenter, 'Battle') if self.game.battle: size = rect.width() // 4 attacker = QRectF(rect.x() + size, 30 + rect.y(), size - 10, size - 10) defender = QRectF(rect.x() + 2 * size, 30 + rect.y(), size - 10, size - 10) self.qp.setPen(self.color) self.qp.setFont(self.font) self.qp.setBrush( QColor(*player_color(self.game.battle['atk_name']))) self.qp.drawRect(attacker) self.qp.drawText(attacker, Qt.AlignCenter, str(self.game.battle['atk_dice'])) self.qp.setBrush( QColor(*player_color(self.game.battle['def_name']))) self.qp.drawRect(defender) self.qp.drawText(defender, Qt.AlignCenter, str(self.game.battle['def_dice'])) self.game.battle = False else: size = rect.width() // 4 self.qp.setBrush(QColor(230, 230, 230)) attacker = QRectF(rect.x() + size, 30 + rect.y(), size - 10, size - 10) deffender = QRectF(rect.x() + 2 * size, 30 + rect.y(), size - 10, size - 10) self.qp.drawRect(attacker) self.qp.drawRect(deffender)
def save_font_png(font): # global border Bl = 10 Br = 10 Bt = 7 Bb = 7 # border bl = 7 br = 7 bt = 27 bb = 10 # pixel size pw = 4 ph = 4 # char spacing sw = 6 sh = 20 # grid thickness gw = 1 gh = 1 # text offset ch = -22 pixmap = QPixmap(Bl + (bl + (pw + gw) * 5 - gw + br) * 16 + Br, Bt + (bt + (ph + gh) * 8 - gh + bb) * 16 + Bb) painter = QPainter(pixmap) label_font = QFont('Courier New', 12) label_font.setBold(True) painter.setPen(Qt.black) painter.setFont(label_font) painter.fillRect(0, 0, pixmap.width(), pixmap.height(), Qt.white) xb = Bl + bl yb = Bt + bt counter = 0 for glyph in font: if counter > 31 and counter < 127: text = chr(counter) background = QColor(200, 255, 200) else: text = (u'%02X' % counter) + u'\u2095' background = Qt.white if counter > 0: painter.fillRect(xb - bl, yb - bt, bl + (pw + gw) * 5 - gw + br, bt + (ph + gh) * 8 - gh + bb, background) painter.drawText(xb, yb + ch, (pw + gw) * 5 - gw, 100, Qt.AlignHCenter | Qt.TextDontClip, text) xo = 0 for column in glyph: for bit, pixel in enumerate(column): painter.fillRect(xb + xo, yb + (ph + gh) * bit, pw, ph, Qt.black if pixel else Qt.lightGray) xo += pw + gw yb += (ph + gh) * 8 - gh + bb + bt counter += 1 if counter % 16 == 0: xb += (pw + gw) * 5 - gw + br + bl yb = Bt + bt painter.end() pixmap.save('font.png', 'PNG')
class QRoundProgressBar(QWidget): """Custom QWidget to implement a round progress bar. :attr: PositionLeft: Left position on the round progressbar in degrees. (180 degrees) :attr: PositionTop: Top position on the round progressbar in degrees. (90 degrees) :attr: PositionRight: Right position on the round progressbar in degrees. (0 degrees) :attr: PositionBottom: Bottom position on the round progressbar in degrees. (-90 degrees) """ PositionLeft = POSITION_LEFT PositionTop = POSITION_TOP PositionRight = POSITION_RIGHT PositionBottom = POSITION_BOTTOM def __init__(self, parent=None, start_value: float = 0, end_value: float = 100, value: float = 0) -> None: """Initialise the round progressbar :param parent = None: Parent object for the round progressbar. :param start_value = 0: Starting value for the progressbar. :param end_value = 0: Ending value for the progressbar. :param value = 0: Current value for the progressbar. """ super().__init__(parent) self._start_value = start_value self._end_value = end_value self._value = value # Template to display text at the center of progressbar (Eg. 80 / 100) self._str_template = Template('$value / $end_value') self._font = QFont(FONT_NAME, FONT_SIZE, QFont.Bold) self._margin_percent = Margin(top=DEFAULT_MARGIN, right=DEFAULT_MARGIN, bottom=DEFAULT_MARGIN, left=DEFAULT_MARGIN) self._pen_width = DEFAULT_PEN_WIDTH self.initUI() @property def start_value(self) -> float: """Starting value for the progressbar. getter: Get the starting value of the progressbar. setter: Set the starting value of the progressbar. """ return self._start_value @start_value.setter def start_value(self, val: float) -> None: self._start_value = val @property def end_value(self) -> float: """Ending value for the progressbar. getter: Get the ending value of the progressbar. setter: Set the ending value of the progressbar. """ return self._end_value @end_value.setter def end_value(self, val: float) -> None: self._end_value = val def set_range(self, start: float, end: float): """Set the starting and the ending value for progressbar. :param start: float: Starting value for the progressbar. :param end: float: Ending value for the progressbar. """ self._start_value = start self._end_value = end # After the range is changed, update the UI to reflect changes self.update() @property def value(self) -> float: """Current value for the progressbar. getter: Get the current value of the progressbar. setter: Set the current value of the progressbar. """ return self._value @value.setter def value(self, value: float) -> None: self._value = value # After the value is updated, update the UI to reflect changes self.update() @property def font(self) -> QFont: """Font object to be used for the text at the center of progressbar. getter: Get the font object used for the text at the center of progressbar. setter: Set the font object used for the text at the center of progressbar. """ return self._font @font.setter def font(self, font: QFont) -> None: self._font = font @property def pen_width(self) -> int: """Width of the pen to be used to draw the circles. getter: Get the width of the pen used to draw the circles. setter: Set the width of the pen used to draw the circles. """ return self._pen_width @pen_width.setter def pen_width(self, width: int) -> None: self._pen_width = width def initUI(self) -> None: """Set the minimum size of the progressbar """ self.setMinimumSize(200, 200) def getAdjustedRect(self) -> QRectF: """Returns a rectangle after adding margin to the base rectangle, with same center. """ leftMargin = (self._margin_percent.left * self._side) / 100 rightmargin = (self._margin_percent.right * self._side) / 100 topMargin = (self._margin_percent.top * self._side) / 100 bottomMargin = (self._margin_percent.bottom * self._side) / 100 adjustedRect = self._baseRect.adjusted(leftMargin, rightmargin, -topMargin, -bottomMargin) return adjustedRect def paintEvent(self, event: QPaintEvent) -> None: """Update the UI, called regularly by Qt whenever self.update is called. :param event: QPaintEvent: QPaint event that is passed to the method by Qt. """ self._painter = QPainter() self._painter.begin(self) self._painter.setRenderHint(QPainter.TextAntialiasing, True) self._painter.setRenderHint(QPainter.HighQualityAntialiasing, True) self.drawWidget() self._painter.end() def drawWidget(self) -> None: """Draw the Progressbar and the text at the center. """ size = self.size() self._side = SIDE_FRACTION * min(size.width(), size.height()) self._baseRect = QRectF(0, 0, self._side, self._side) self.drawProgressBar() self.drawCenterText() def drawProgressBar(self) -> None: """Draw the round progressbar. First a circle is drawn at the center of the available space. Next an arc is drawn depending the current value. Angle of arc = (current_value - start_value) / (end_value - start_value) * 360 """ adjustedRect = self.getAdjustedRect() with DrawingPainter( self._painter, QPen(Qt.green, self._pen_width + 6, Qt.SolidLine, Qt.FlatCap)) as painter: painter.drawEllipse(adjustedRect) with DrawingPainter( self._painter, QPen(Qt.red, self._pen_width, Qt.SolidLine, Qt.FlatCap)) as painter: startAngle = self.PositionTop * PYQT_ANGLE_PRECISION endAngle = -int(((self.value - self.start_value) / (self.end_value - self.start_value)) * FULL_ANGLE * PYQT_ANGLE_PRECISION) painter.drawArc(adjustedRect, startAngle, endAngle) def drawCenterText(self) -> None: """Draw text at the center of the Progressbar in the form "current_value / end_value" """ substitution = { 'value': str(round(self.value, 2)), 'end_value': str(round(self.end_value, 2)) } # type: Dict[str, str] text = self._str_template.substitute(substitution) self._painter.setFont(self.font) self._painter.drawText(self._baseRect, Qt.AlignCenter, text)
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setFont(self.__font) painter.setPen(self.__pen_line) metrics = QFontMetrics(self.__font) # text_height = metrics.height() text_width = max( metrics.size(Qt.TextExpandTabs, name).width() for name in self.__names) * 1.2 self.__item_width = self.width() / float(len(self.__names)) # self.__item_height = 2.5 * text_height self.__item_height = self.frameGeometry().height( ) # modified to auto-fit height from layout for i, name in enumerate(self.__names): if self.__availables[i]: color = self.__color_unselected else: color = self.__color_notavailable if i == 0: if len(self.__names) == 1: self.__paintOnlyOne(painter, color) else: self.__paintStart(painter, color) elif i == len(self.__names) - 1: self.__paintStop(painter, self.__item_width * i, color) else: self.__paintMiddle(painter, self.__item_width * i, color) if self.__selected is not None: if self.__mode == 'stop': pos_x = self.__selected * self.__item_width if self.__selected == 0: if len(self.__names) == 1: self.__paintOnlyOne(painter, self.__color_selected) else: self.__paintStart(painter, self.__color_selected) elif self.__selected == len(self.__names) - 1: self.__paintStop(painter, self.__item_width * self.__selected, self.__color_selected) else: self.__paintMiddle(painter, self.__item_width * self.__selected, self.__color_selected) else: self.__paintMiddle(painter, self.__pos, self.__color_selected) painter.setPen(self.__pen_text) for i, name in enumerate(self.__names): if i == self.__selected: painter.setPen(self.__textColor_selected) else: painter.setPen(self.__textColor_unselected) painter.drawText( QRect(self.__item_width * i, 0, self.__item_width, self.__item_height), Qt.AlignCenter, name) painter.end() self.setMinimumHeight(self.__item_height) self.setMinimumWidth(text_width * len(self.__names))
def btnStart_Click(self): global combination_series # List of lists containing min_series of 5 correct results -- Added by Denis Lazor global parameter_name # Name of parameter used for writing its data to .csv file -- Added by Denis Lazor global best_fit_values # List containing best fitness values for every of 5 experiments per combination -- Added by Denis Lazor global best_individual # Saving best individuals for drawing the best solution -- Added by Denis Lazor global ELITE_SIZES global POPULATION_SIZES global MUTATION_SIZES # Checking if files are empty or not -- Added by Denis Lazor csv_contains = os.stat("graphs_csv/original.csv").st_size != 0 if csv_contains: clear_all_csv() n = 5000 # Automation for all necessary combinations -- Added by Denis Lazor for p in POPULATION_SIZES: for m in MUTATION_SIZES: for e in ELITE_SIZES: for i in range(5): # Set global variables global stop_evolution global q_min_series global q_max_series global q_avg_series stop_evolution = False q_min_series.clear() q_max_series.clear() q_avg_series.clear() # Set global variables from information on UI global NGEN global POP_SIZE global MUTPB global NELT NGEN = n POP_SIZE = p MUTPB = m NELT = e global border_check border_check = self.cbxBorder.isChecked() # Loading Croatia map self.img = QPixmap(620, 600) self.img.load('Croatia620.png') self.frameWorld.img = self.img # Drawing towns painter = QPainter(self.img) painter.setPen(QPen(Qt.black, 10, Qt.SolidLine)) painter.setFont(QFont('Arial', 12)) for i in range(len(gradovi)): x, y = GlobToImgCoords(sirine[i], duzine[i]) painter.drawPoint(x, y) painter.drawText(x + 5, y + 5, gradovi[i]) painter.end() # Redrawing frames self.frameWorld.repaint() app.processEvents() ####Initialize deap GA objects#### # Make creator that minimize. If it would be 1.0 instead od -1.0 than it would be maxmize creator.create("FitnessMin", base.Fitness, weights=(-1.0, )) # Create an individual (a blueprint for cromosomes) as a list with a specified fitness type creator.create("Individual", list, fitness=creator.FitnessMin) # Create base toolbox for finishing creation of a individual (cromosome) self.toolbox = base.Toolbox() # This is if we want a permutation coding of genes in the cromosome self.toolbox.register("indices", random.sample, range(IND_SIZE), IND_SIZE) # initIterate requires that the generator of genes (such as random.sample) generates an iterable (a list) variable self.toolbox.register("individual", tools.initIterate, creator.Individual, self.toolbox.indices) # Create a population of individuals (cromosomes). The population is then created by toolbox.population(n=300) where 'n' is the number of cromosomes in population self.toolbox.register("population", tools.initRepeat, list, self.toolbox.individual) # Register evaluation function self.toolbox.register("evaluate", evaluateInd) # Register what genetic operators to use self.toolbox.register( "mate", tools.cxUniformPartialyMatched, indpb=0.2 ) # Use uniform recombination for permutation coding # Permutation coding self.toolbox.register("mutate", tools.mutShuffleIndexes, indpb=0.2) self.toolbox.register( "select", tools.selTournament, tournsize=3) # Use tournament selection ################################## # Generate initial poplation. Will be a member variable so we can easely pass everything to new thread self.pop = self.toolbox.population(n=POP_SIZE) # Evaluate initial population, we map() the evaluation function to every individual and then assign their respective fitness, map runs evaluate function for each individual in pop fitnesses = list(map(self.toolbox.evaluate, self.pop)) for ind, fit in zip(self.pop, fitnesses): ind.fitness.values = fit # Assign calcualted fitness value to individuals # Extracting all the fitnesses of all individuals in a population so we can monitor and evovlve the algorithm until it reaches 0 or max number of generation is reached self.fits = [ind.fitness.values[0] for ind in self.pop] # Disable start and enable stop self.btnStart.setEnabled(False) self.btnStop.setEnabled(True) self.gaParams.setEnabled(False) self.cbxBorder.setEnabled(False) self.cbxNoVis.setEnabled(False) # Start evolution self.evolve() # Best fitness value -- Added by Denis Lazor best_fit = np.array(min(best_fit_values))[0] mean_fit = min( best_fit_values, key=lambda x: abs(x - statistics.mean( (np.asarray(best_fit_values)).flatten())))[0] # Index of best fitness value -- Added by Denis Lazor best_fit_idx = best_fit_values.index(best_fit) write_to_file(combination_series[best_fit_idx], parameter_name) # First name will be "original", second one "elites" -- Added by Denis Lazor parameter_name = "elites" print_results(p, m, e, best_fit, mean_fit, NGEN) # Clearing past lists -- Added by Denis Lazor combination_series = [] best_fit_values = [] # Reducing number of combinations and changing .csv file for writing -- Added by Denis Lazor ELITE_SIZES = ELITE_SIZES[0:1] parameter_name = "mutation" MUTATION_SIZES = MUTATION_SIZES[0:1] parameter_name = "population" print("Best individual: " + str(best_individual)) self.updateWorldFrame(generateWorldImage( best_individual)) # Drawing best solution -- Added by Denis Lazor
def printDiagram(self, printer, diagramName=""): """ Public method to print the diagram. @param printer reference to a ready configured printer object (QPrinter) @param diagramName name of the diagram (string) """ painter = QPainter() painter.begin(printer) offsetX = 0 offsetY = 0 widthX = 0 heightY = 0 font = QFont("times", 10) painter.setFont(font) fm = painter.fontMetrics() fontHeight = fm.lineSpacing() marginX = printer.pageRect().x() - printer.paperRect().x() marginX = \ Preferences.getPrinter("LeftMargin") * int( printer.resolution() / 2.54) - marginX marginY = printer.pageRect().y() - printer.paperRect().y() marginY = \ Preferences.getPrinter("TopMargin") * int( printer.resolution() / 2.54) - marginY width = printer.width() - marginX \ - Preferences.getPrinter("RightMargin") * int( printer.resolution() / 2.54) height = printer.height() - fontHeight - 4 - marginY \ - Preferences.getPrinter("BottomMargin") * int( printer.resolution() / 2.54) border = self.border == 0 and 5 or self.border rect = self._getDiagramRect(border) diagram = self.__getDiagram(rect) finishX = False finishY = False page = 0 pageX = 0 pageY = 1 while not finishX or not finishY: if not finishX: offsetX = pageX * width pageX += 1 elif not finishY: offsetY = pageY * height offsetX = 0 pageY += 1 finishX = False pageX = 1 if (width + offsetX) > diagram.width(): finishX = True widthX = diagram.width() - offsetX else: widthX = width if diagram.width() < width: widthX = diagram.width() finishX = True offsetX = 0 if (height + offsetY) > diagram.height(): finishY = True heightY = diagram.height() - offsetY else: heightY = height if diagram.height() < height: finishY = True heightY = diagram.height() offsetY = 0 painter.drawPixmap(marginX, marginY, diagram, offsetX, offsetY, widthX, heightY) # write a foot note s = self.tr("{0}, Page {1}").format(diagramName, page + 1) tc = QColor(50, 50, 50) painter.setPen(tc) painter.drawRect(marginX, marginY, width, height) painter.drawLine(marginX, marginY + height + 2, marginX + width, marginY + height + 2) painter.setFont(font) painter.drawText(marginX, marginY + height + 4, width, fontHeight, Qt.AlignRight, s) if not finishX or not finishY: printer.newPage() page += 1 painter.end()
def seed_img(self, is_seed=True): if is_seed: try: cseed = self.get_seed() except UserCancelled: return except InvalidPassword as e: self.d.show_error(str(e)) return if not cseed: self.d.show_message(_("This wallet has no seed")) return txt = cseed.upper() else: txt = self.txt.upper() img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono) bitmap = QBitmap.fromImage(img, Qt.MonoOnly) bitmap.fill(Qt.white) painter = QPainter() painter.begin(bitmap) QFontDatabase.addApplicationFont( os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf')) if len(txt) < 102: fontsize = 15 linespace = 15 max_letters = 17 max_lines = 6 max_words = 3 else: fontsize = 12 linespace = 10 max_letters = 21 max_lines = 9 max_words = int(max_letters / 4) font = QFont('Source Sans Pro', fontsize, QFont.Bold) font.setLetterSpacing(QFont.PercentageSpacing, 100) font.setPixelSize(fontsize) painter.setFont(font) seed_array = txt.split(' ') for n in range(max_lines): nwords = max_words temp_seed = seed_array[:nwords] while len(' '.join(map(str, temp_seed))) > max_letters: nwords = nwords - 1 temp_seed = seed_array[:nwords] painter.drawText( QRect(0, linespace * n, self.SIZE[0], self.SIZE[1]), Qt.AlignHCenter, ' '.join(map(str, temp_seed))) del seed_array[:nwords] painter.end() img = bitmap.toImage() if (self.rawnoise == False): self.make_rawnoise() self.make_cypherseed(img, self.rawnoise, False, is_seed) return img
def save_as_pdf(self): filename = QFileDialog.getSaveFileName(self, 'Save to PDF', 'c:\\', "*.pdf") if filename != ('', ''): if os.path.exists(filename[0]): try: infile = PdfFileReader(filename[0], 'rb') except: error = QMessageBox() error.setIcon(QMessageBox.Warning) error.setStandardButtons(QMessageBox.Ok) error.setText( "File could not be written to. If the file is currently open, try closing it" ) error.exec_() return if infile.getNumPages() == 0: print("HERE!") doc = QTextDocument() doc.print(printer) printer = QPrinter() printer.setPageSize(QPrinter.A4) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(filename[0]) painter = QPainter() font = QFont("times") font.setPointSize(12) x = painter.begin(printer) if x == False: error = QMessageBox() error.setIcon(QMessageBox.Warning) error.setStandardButtons(QMessageBox.Ok) error.setText( "File could not be saved. If the file is currently open, try closing it" ) error.exec_() return painter.setFont(font) for i in range(0, self.symbol_tests.count()): cur_symbol_test = self.symbol_tests.widget(i) if cur_symbol_test.print_visual_context() == False: pixmap = cur_symbol_test.get_symbol() pixmap = pixmap.scaled(350, 350) painter.drawPixmap(30, 100, pixmap) painter.drawText(750, 20, cur_symbol_test.get_page()) painter.drawText( 420, 200, 350, 400, QtCore.Qt.TextWordWrap, "Context: " + cur_symbol_test.get_context()) painter.drawText(30, 600, cur_symbol_test.get_question1()) painter.drawText(30, 830, cur_symbol_test.get_question2()) cur_pen = painter.pen() line_pen = QPen() line_pen.setWidth(2) painter.setPen(line_pen) painter.drawLine(70, 656, 600, 656) painter.drawLine(70, 712, 600, 712) painter.drawLine(70, 768, 600, 768) painter.drawLine(70, 886, 600, 886) painter.drawLine(70, 942, 600, 942) painter.drawLine(70, 998, 600, 998) painter.setPen(cur_pen) else: pixmap = cur_symbol_test.get_visual_context() pixmap = pixmap.scaled(300, 300) painter.drawPixmap(200, 10, pixmap) pixmap = cur_symbol_test.get_symbol() pixmap = pixmap.scaled(250, 250) painter.drawPixmap(225, 320, pixmap) painter.drawText(750, 20, cur_symbol_test.get_page()) #painter.drawText(420, 200, 350, 400, QtCore.Qt.TextWordWrap, "Context: " + cur_symbol_test.get_context()) painter.drawText(30, 600, cur_symbol_test.get_question1()) painter.drawText(30, 830, cur_symbol_test.get_question2()) cur_pen = painter.pen() line_pen = QPen() line_pen.setWidth(2) painter.setPen(line_pen) painter.drawLine(70, 656, 600, 656) painter.drawLine(70, 712, 600, 712) painter.drawLine(70, 768, 600, 768) painter.drawLine(70, 886, 600, 886) painter.drawLine(70, 942, 600, 942) painter.drawLine(70, 998, 600, 998) painter.setPen(cur_pen) if (i < self.symbol_tests.count() - 1): printer.newPage() painter.end()