def erase_area(image, x, y, w, h): painter = QPainter() painter.begin(image) painter.setCompositionMode(QPainter.CompositionMode_Clear) painter.fillRect(x, y, w, h, Qt.transparent) painter.end()
def drawMarkerLine(self, event): scenePos = self.mapToScene(event.pos()) painter = QPainter(self.mask_pixmap) painter.setCompositionMode(self.current_painting_mode) painter.setPen( QPen(self.brush_fill_color, self.brush_diameter, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(self.lastPoint, scenePos) self._overlayHandle.setPixmap(self.mask_pixmap) # In case of direct mask paint mode, we need to paint on the mask as well if self.direct_mask_paint: if not self.d_rgb2gray: raise RuntimeError( "Cannot use direct mask painting since there is no color conversion rules set." ) painter = QPainter(self._offscreen_mask) painter.setCompositionMode(self.current_painting_mode) tc = self.d_rgb2gray[self.brush_fill_color.name()] painter.setPen( QPen(QColor(tc, tc, tc), self.brush_diameter, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(self.lastPoint, scenePos) self.lastPoint = scenePos
def make_cypherseed(self, img, rawnoise, calibration=False, is_seed = True): img = img.convertToFormat(QImage.Format_Mono) p = QPainter() p.begin(img) p.setCompositionMode(26) #xor p.drawImage(0, 0, rawnoise) p.end() cypherseed = self.pixelcode_2x2(img) cypherseed = QBitmap.fromImage(cypherseed) cypherseed = cypherseed.scaled(self.f_size, Qt.KeepAspectRatio) cypherseed = self.overlay_marks(cypherseed, True, calibration) if not is_seed: self.filename_prefix = 'custom_secret_' self.was = _('Custom secret') else: self.filename_prefix = self.wallet_name + '_seed_' self.was = self.wallet_name + ' ' + _('seed') if self.extension: self.ext_warning(self.c_dialog) if not calibration: self.toPdf(QImage(cypherseed)) QDesktopServices.openUrl(QUrl.fromLocalFile(self.get_path_to_revealer_file('.pdf'))) cypherseed.save(self.get_path_to_revealer_file('.png')) self.bcrypt(self.c_dialog) return cypherseed
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap(mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
def generate_qr_code(text): qr = qrcode.QRCode(version=None, error_correction=qrcode.constants.ERROR_CORRECT_H, border=4, box_size=10) qr.add_data(text) qr.make(fit=True) qr_img = qr.make_image(image_factory=qrcode.image.svg.SvgPathImage) stream = io.BytesIO() qr_img.save(stream) renderer = QSvgRenderer() renderer.load(stream.getvalue()) final_img = QImage(600, 600, QImage.Format_ARGB32) final_img.fill(QColor(0xF4, 0xF4, 0xF4)) painter = QPainter() painter.begin(final_img) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) renderer.render( painter, QRectF(0, 0, final_img.rect().width(), final_img.rect().height())) painter.end() pix = QPixmap.fromImage(final_img) return pix
def paintEvent(self, event): painter = QPainter(self) image = self._alignment.image() painter.drawImage(self.rect(), QImage(image.tobytes(), *image.shape, QImage.Format_Grayscale8)) painter.setCompositionMode(QPainter.CompositionMode_Lighten) pen = QPen() pen.setWidth(self.width()/500) pen.setCapStyle(Qt.RoundCap) painter.scale(self.width() / image.shape[0], self.height() / image.shape[1]) def drawCentre(color, y, x): pen.setColor(color) painter.setPen(pen) length = self.width() /10 painter.translate(x, y) painter.drawLine(-length, -length, length, length) painter.drawLine(-length, length, length, -length) painter.drawEllipse(QPoint(0, 0), length/2, length/2) painter.translate(-x, -y) drawCentre(Qt.red, *self._alignment.reference()) drawCentre(Qt.green, *self._alignment.current())
def _prepare_pixmap(self, qcolor): if self.pixmap is None: return painter = QPainter(self.pixmap) painter.setCompositionMode(QPainter.CompositionMode_SourceAtop) painter.fillRect(self.pixmap.rect(), qcolor) painter.end()
def combine(self, painter, images): """Paint images on the painter. We draw bottom-up, using Darken composition mode, so the lower images remain visible. """ for color, (pos, image) in zip(self.colors, images): # take the alpha component intensity = 255 - color.alpha() if intensity == 255: continue # the image would appear white anyway color = color.rgb() color |= 0x010101 * intensity color |= 0xFF000000 p = QPainter(image) p.setCompositionMode(QPainter.CompositionMode_Lighten) p.fillRect(image.rect(), QColor(color)) p.end() if isinstance(image, QPixmap): painter.drawPixmap(pos, image) else: painter.drawImage(pos, image) painter.setCompositionMode(QPainter.CompositionMode_Darken)
def mouseMoveEvent(self, event): # MAKESHIFT code that "fixes" the coder issue. if (event.buttons() & Qt.LeftButton) & self.drawing: self.line = QLine(self.lastPoint, event.pos()) painterTemp = QPainter(self.imageAbove) painterTemp.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) if (self.strokeCount == 0): painterTemp.setCompositionMode(QPainter.CompositionMode_SourceOver) painterTemp.drawLine(self.line) self.strokeCount = 1 else: self.painterSim.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) self.painterSim.setCompositionMode(QPainter.CompositionMode_SourceOver) self.painterSim.drawLine(self.line) self.painterSim.setPen(QPen(Qt.transparent, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) self.painterSim.setCompositionMode(QPainter.CompositionMode_Source) self.painterSim.drawPoint(event.pos()) self.brushColor = Qt.transparent self.painter.setCompositionMode(QPainter.CompositionMode_SourceOver) painterTemp.end() empty = QPoint(0,0) self.painter.drawImage(empty, self.imageTemp) self.imageTemp.fill(Qt.transparent) self.lastPoint = event.pos() self.update()
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) W = self.width() H = self.height() side = min(W, H) rect = QRect((W-side)/2, (H-side)/2, side, side) painter.drawRect((rect)) painter.setViewport(rect) painter.setWindow(-100, -100, 200, 200) pen = QPen() pen.setWidth(1) pen.setColor(Qt.blue) pen.setStyle(Qt.SolidLine) painter.setPen(pen) linearGrad = QLinearGradient(0, 0, 100, 0) linearGrad.setColorAt(0, Qt.yellow) linearGrad.setColorAt(0.8, Qt.green) linearGrad.setSpread(QGradient.ReflectSpread) painter.setBrush(linearGrad) painter.setCompositionMode(QPainter.CompositionMode_Difference) for i in range(36): painter.drawEllipse(QPoint(50, 0), 50, 50) painter.rotate(10)
def paintEvent(self, e): qp = QPainter() qp.begin(self) fr = self.frameRect() b = self.lineWidth() fr.adjust(b, b, -b, -b) qp.drawImage(QRect(fr.x(), fr.y(), fr.width(), fr.height()), self.image, QRect(0, 0, self.image.width(), self.image.height())) qp.setCompositionMode(QPainter.RasterOp_SourceXorDestination) qp.setPen(QColor(0xff, 0xff, 0xff, 64)) for i in range(1, self.image.width() + 1): x = fr.x() + i * fr.width() / self.image.width() qp.drawLine(x, fr.y(), x, fr.y() + fr.height()) for i in range(1, self.image.height() + 1): y = fr.y() + i * fr.height() / self.image.height() qp.drawLine(fr.x(), y, fr.x() + fr.width(), y) qp.end() super().paintEvent(e)
def captureRegion(x, y, width, height, winId = 0): ''' Captures a region ''' region = QRect(x, y, width, height) screens = [s for s in QApplication.screens() if s.geometry().intersects(region)] # How much to reposition each image so the whole thing is based at 0, 0 offsetX, offsetY = -x, -y final = QImage(width, height, QImage.Format_ARGB32) final.fill(QColor(0, 0, 0, 255)) painter = QPainter() painter.begin(final) painter.setCompositionMode(QPainter.CompositionMode_Source) for screen in screens: geo = screen.geometry() shot = screen.grabWindow(winId, geo.x(), geo.y(), geo.width(), geo.height()) # determine the area to copy toCopy = geo.intersected(region) # Composite it onto the final painter.drawPixmap(toCopy.x() + offsetX, toCopy.y() + offsetY, shot.copy(toCopy)) #end for painter.end() return final
def render(self, painter: QPainter) -> None: if self._item_style == FileItemStyle.SMALLICON: self.paint_smallicon_view(painter) elif self._item_style == FileItemStyle.DETAIL: self.paint_detail_view(painter) else: self.paint(painter) if self.is_selected: painter.save() painter.setCompositionMode(QPainter.CompositionMode_SourceOver) painter.setOpacity(0.5) painter.fillRect(self.tile_rect, QColor(127, 192, 255)) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) painter.setOpacity(1.0) painter.setPen(QColor(96, 127, 255)) painter.setBrush(Qt.NoBrush) painter.drawRect(self.tile_rect) painter.restore() if self.is_cursor: painter.setOpacity(1.0) painter.setPen(QColor(0, 0, 0)) painter.setBrush(QColor(255, 255, 255, 96)) painter.drawRect(self.tile_rect)
def __init__(self, link: Link, *args, **kwargs): super().__init__(*args, **kwargs) self.link = link layout = QHBoxLayout() pm_remove = QPixmap('imgs/close-thick.png') pm_remove_painter = QPainter(pm_remove) pm_remove_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) pm_remove_painter.fillRect(pm_remove.rect(), QColor(0, 102, 202)) pm_remove_painter.end() pic_remove = QLabel() pic_remove.mousePressEvent = self.on_remove pic_remove.setPixmap(pm_remove) layout.addWidget(pic_remove) if link.active: pm_switch = QPixmap('imgs/toggle-switch.png') else: pm_switch = QPixmap('imgs/toggle-switch-off.png') pm_switch_painter = QPainter(pm_switch) pm_switch_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) if link.active: pm_switch_painter.fillRect(pm_switch.rect(), QColor(0, 192, 0)) else: pm_switch_painter.fillRect(pm_switch.rect(), QColor(255, 64, 0)) pm_switch_painter.end() pic_switch = QLabel() pic_switch.mousePressEvent = self.on_switch pic_switch.setPixmap(pm_switch) layout.addWidget(pic_switch) self.setLayout(layout)
def paintEvent(self, event): p = QPainter(self) if self.scrollEnabled: self.buffer.fill(qRgba(0, 0, 0, 0)) pb = QPainter(self.buffer) pb.setPen(p.pen()) pb.setFont(p.font()) x = min(-self.scrollPos, 0) + self.leftMargin while x < self.width(): pb.drawStaticText( QPointF(x, (self.height() - self.wholeTextSize.height()) / 2) + QPoint(2, 2), self.staticText) x += self.wholeTextSize.width() #Apply Alpha Channel pb.setCompositionMode(QPainter.CompositionMode_DestinationIn) pb.setClipRect(self.width() - 15, 0, 15, self.height()) pb.drawImage(0, 0, self.alphaChannel) pb.setClipRect(0, 0, 15, self.height()) #initial situation: don't apply alpha channel in the left half of the image at all; apply it more and more until scrollPos gets positive if self.scrollPos < 0: pb.setOpacity((max(-8, self.scrollPos) + 8) / 8.0) pb.drawImage(0, 0, self.alphaChannel) p.drawImage(0, 0, self.buffer) else: x = (self.width() - self.wholeTextSize.width()) / 2 y = (self.height() - self.wholeTextSize.height()) / 2 p.drawStaticText(QPointF(x, y), self.staticText)
def paintMotionHeatmap(self, paintEvent): return #Heatmap got delayed. Just return for now… if not self.totalRecordedFrames: return p = QPainter(self.uiTimelineVisualization) #Draw the scrollbar motion heatmap. p.setCompositionMode(QPainter.CompositionMode_Darken) p.drawImage(QtCore.QPoint(0,0), self.motionHeatmap) #Mark the heatmap segments. p.setCompositionMode(QPainter.CompositionMode_SourceOver) p.setPen(QColor(255,255,255,255//2)) path = QPainterPath() for border in [rs['start'] for rs in self.recordedSegments[1:]]: x = round(border / self.totalRecordedFrames * (self.uiTimelineVisualization.width()-1))+0.5 path.moveTo(x, 0); path.lineTo(x, self.uiTimelineVisualization.height()) p.drawPath(path) #Mark save start/save end. mark = self.markedStart if self.markedStart is not None else self.markedEnd if mark is not None: p.setPen(QColor(100,230,100,255)) path = QPainterPath() x = round(mark / self.totalRecordedFrames * (self.uiTimelineVisualization.width()-1))+0.5 path.moveTo(x, 0); path.lineTo(x, self.uiTimelineVisualization.height()) p.drawPath(path)
def __grabRegion(self): """ Private method to grab the selected region (i.e. do the snapshot). """ pol = QPolygon(self.__selection) if not pol.isEmpty(): self.__grabbing = True xOffset = self.__pixmap.rect().x() - pol.boundingRect().x() yOffset = self.__pixmap.rect().y() - pol.boundingRect().y() translatedPol = pol.translated(xOffset, yOffset) pixmap2 = QPixmap(pol.boundingRect().size()) pixmap2.fill(Qt.transparent) pt = QPainter() pt.begin(pixmap2) if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff): pt.setRenderHints( QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform, True) pt.setBrush(Qt.black) pt.setPen(QPen(QBrush(Qt.black), 0.5)) pt.drawPolygon(translatedPol) pt.setCompositionMode(QPainter.CompositionMode_SourceIn) else: pt.setClipRegion(QRegion(translatedPol)) pt.setCompositionMode(QPainter.CompositionMode_Source) pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect()) pt.end() self.grabbed.emit(pixmap2)
def pixmap(name, size, mode, state): """Returns a (possibly cached) pixmap of the name and size with the default text color. The state argument is ignored for now. """ if mode == QIcon.Selected: color = QApplication.palette().highlightedText().color() else: color = QApplication.palette().text().color() key = (name, size.width(), size.height(), color.rgb(), mode) try: return _pixmaps[key] except KeyError: i = QImage(size, QImage.Format_ARGB32_Premultiplied) i.fill(0) painter = QPainter(i) # render SVG symbol QSvgRenderer(os.path.join(__path__[0], name + ".svg")).render(painter) # recolor to text color painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(i.rect(), color) painter.end() # let style alter the drawing based on mode, and create QPixmap pixmap = QApplication.style().generatedIconPixmap( mode, QPixmap.fromImage(i), QStyleOption()) _pixmaps[key] = pixmap return pixmap
def paintEvent(self, event): pp = QPainter(self.pix) # 根据鼠标指针前后两个位置绘制直线 pp.setPen(self.__pen) if self.crop_mode: pp = QPainter(self) pp.setPen(QPen(Qt.red, 4, Qt.SolidLine)) pp.drawPixmap(0, 0, self.bg) if self.lastPoint is not None: pp.drawRect(QRectF(self.lastPoint, self.endPoint)) else: if self.painter_status == self.ERASE: pen = QPen() pen.setWidth(10) pp.setCompositionMode(QPainter.CompositionMode_Clear) pp.setPen(pen) if self.lastPoint is not None: pp.drawLine(self.lastPoint, self.endPoint) # 让前一个坐标值等于后一个坐标值, # 这样就能实现画出连续的线 self.lastPoint = self.endPoint painter = QPainter(self) painter.drawPixmap(0, 0, self.bg) painter.drawPixmap(0, 0, self.pix) # 在画布上画出
def fillMarker(self, event): scenePos = self.mapToScene(event.pos()) painter = QPainter(self.mask_pixmap) painter.setCompositionMode(self.current_painting_mode) painter.setPen(self.brush_fill_color) painter.setBrush(self.brush_fill_color) # Get the coordinates of where to draw a0 = scenePos.x() - self.brush_diameter / 2 b0 = scenePos.y() - self.brush_diameter / 2 r0 = self.brush_diameter # Finally, draw painter.drawEllipse(a0, b0, r0, r0) # TODO: With really large images, update is rather slow. Must somehow fix this. # It seems that the way to approach hardcore optimization is to switch to OpenGL # for all rendering purposes. This update will likely come much later in the tool's # lifecycle. self._overlayHandle.setPixmap(self.mask_pixmap) # In case of direct mask paint mode, we need to paint on the mask as well if self.direct_mask_paint: if not self.d_rgb2gray: raise RuntimeError( "Cannot use direct mask painting since there is no color conversion rules set." ) painter = QPainter(self._offscreen_mask) painter.setCompositionMode(self.current_painting_mode) tc = self.d_rgb2gray[self.brush_fill_color.name()] painter.setPen(QColor(tc, tc, tc)) painter.setBrush(QColor(tc, tc, tc)) painter.drawEllipse(a0, b0, r0, r0) self.lastPoint = scenePos
def launch_main(xml_fname=None, introspect_fname=None): app = QApplication(sys.argv) import time start = time.time() splash_fname = utils.get_resource_path('icons/splash.jpg') splash_pix = QPixmap(splash_fname) size = splash_pix.size()*.35 splash_pix = splash_pix.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) # # below makes the pixmap half transparent painter = QPainter(splash_pix) painter.setCompositionMode(painter.CompositionMode_DestinationAtop) painter.end() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.show() app.processEvents() time.sleep(2) app.processEvents() mdwiz = PyMdWizardMainForm() mdwiz.show() splash.finish(mdwiz) if xml_fname is not None and os.path.exists(xml_fname): mdwiz.open_file(xml_fname) if introspect_fname is not None and os.path.exists(introspect_fname): mdwiz.metadata_root.eainfo.detaileds[0].populate_from_fname(introspect_fname) mdwiz.metadata_root.eainfo.ui.fgdc_eainfo.setCurrentIndex(1) app.exec_()
def repaintBaseImage(self): shell_image = self._ghost.getShellImage() self._base_image = QImage(self._size, QImage.Format_ARGB32_Premultiplied) painter = QPainter(self._base_image) painter.setCompositionMode(QPainter.CompositionMode_Source) painter.fillRect(self._base_image.rect(), Qt.transparent) painter.end() del painter if self._surface is None: return if len(self._surface.elements) > 0: for i, ele in self._surface.elements.items(): if ele.filename in shell_image: offset = self._draw_offset + ele.offset kikka.helper.drawImage(self._base_image, shell_image[ele.filename], offset.x(), offset.y(), ele.PaintType) else: img = self.getShellImage(self._surface.ID) painter = QPainter(self._base_image) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) painter.drawImage(self._draw_offset, img) painter.end() # self._base_image.save("_base_image.png") pass
def paintEvent(self, e): qp = QPainter() qp.begin(self) qp.setCompositionMode(QPainter.CompositionMode_SourceOver) img = QPixmap(self.imgInst.getPath()) qp.drawPixmap(0, 0, img) self.drawBrushes(qp) qp.end()
def mouseMoveEvent(self, e): """ Handles the snippet capture and drag drop initialization based off of: http://stackoverflow.com/questions/28258050/drag-n-drop-button-and-drop-down-menu-pyqt-qt-designer Parameters ---------- e : qt event Returns ------- None """ if e.buttons() != Qt.LeftButton: if hasattr(self, 'drag_start_pos'): delattr(self, 'drag_start_pos') if not hasattr(self, 'drag_start_pos'): return if not (e.pos() - self.drag_start_pos).manhattanLength() > 75: return modifiers = QApplication.keyboardModifiers() if not modifiers == Qt.ControlModifier: return mime_data = self.get_mime() # let's make it fancy. we'll show a "ghost" of the button as we drag # grab the button to a pixmap pixmap = self.grab() size = pixmap.size() * .65 half_pixmap = pixmap.scaled(size, Qt.KeepAspectRatio, transformMode=Qt.SmoothTransformation) # below makes the pixmap half transparent painter = QPainter(half_pixmap) painter.setCompositionMode(painter.CompositionMode_DestinationAtop) painter.fillRect(half_pixmap.rect(), QColor(0, 0, 0, 127)) font = QFont() font.setFamily('Arial') font.setPointSize(15) font.setBold(True) painter.setFont(font) painter.setPen(Qt.red) painter.drawText(half_pixmap.rect(), Qt.AlignCenter, self.drag_label) painter.end() drag = QDrag(self) drag.setMimeData(mime_data) drag.setPixmap(half_pixmap) drag.setHotSpot(e.pos()) # dropAction = drag.exec_(Qt.CopyAction | Qt.MoveAction) # dropAction = drag.exec_(Qt.TargetMoveAction) dropAction = drag.exec_() e.ignore()
def show_original_image(self): m = 6 * (self.set - 1) + self.id self.newpathdir = os.path.join( os.path.join(self.curr_dir_destination, self.destination_directory), "Cropped") newpath = os.path.join(self.newpathdir, os.path.basename(self.img_files[m])) flag = 0 # the image has been cropped, so delete the file and replace the name in cropped.txt, global array, also display for i in range(len(self.img_files)): if self.img_files[i] == newpath: flag = 1 if os.path.exists(newpath): os.remove(newpath) # old path before crop (in source dir or destination dir) is written in img_files.txt with open("Img_files.txt", "r") as file: img_files_old = file.read().splitlines() file.close() oldpath = img_files_old[m] self.img_files[i] = oldpath with open("Img_files_cropped.txt", "w") as file: for j in range(len(self.img_files)): file.write(self.img_files[j]) file.write("\n") file.close() # Replacing border with False, since crop image is removed self.img_files_border[m] = False # To show in the corresponding label, determine label id first k = m - (self.set - 1) * 6 image = QImage(self.img_files[m]) image = image.convertToFormat( QImage.Format_ARGB8565_Premultiplied) p = QPainter(image) p.setCompositionMode(QPainter.CompositionMode_DestinationIn) p.fillRect(image.rect(), QColor(0, 0, 0, self.transparency)) p.end() pixmap = QPixmap(image) w = int(self.labels[k].width() - 4.0) h = int(self.labels[k].height() - 4.0) smaller_pixmap = pixmap.scaled(w, h, Qt.KeepAspectRatio, Qt.FastTransformation) self.labels[k].setScaledContents(True) self.labels[k].setFrameShadow(QFrame.Plain) self.labels[k].setPixmap(smaller_pixmap) self.btn_img[k] = self.img_files[m] # The image has not been cropped, so no action is needed if flag == 0: pass
def setRoundMask(self): bmp = QPixmap(self.size()) bmp.fill(Qt.white) p = QPainter(bmp) p.setRenderHint(QPainter.Antialiasing) p.setBrush(QBrush(Qt.white)) p.setCompositionMode(QPainter.CompositionMode_Clear) p.drawRoundedRect(0, 0, self.width(), self.height(), 3, 3) p.end() self.setMask(QRegion(QBitmap(bmp)))
def paintEvent(self, event): # super().paintEvent(event) if self.isDrawing: print('Painting Start') p = QPainter(self) p.setCompositionMode(QPainter.CompositionMode_SourceOver) p.setRenderHint(QPainter.Antialiasing) p.setPen(QPen(Qt.blue, 4, Qt.SolidLine)) p.drawRect(self.startX, self.startY, self.endX, self.endY)
def _loadImage(self, file_name): image = QImage() image.load(file_name) fixed_image = QImage(ImageSize, QImage.Format_ARGB32_Premultiplied) painter = QPainter(fixed_image) painter.setCompositionMode(QPainter.CompositionMode_Source) painter.fillRect(fixed_image.rect(), Qt.transparent) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) painter.drawImage(imagePos(image), image) painter.end() return fixed_image
def _draw_images(self, images: List[QImage]): result = QImage(images[0].size(), QImage.Format_ARGB32_Premultiplied) painter = QPainter(result) painter.setCompositionMode(QPainter.CompositionMode_Source) painter.fillRect(images[0].rect(), Qt.transparent) painter.setCompositionMode(self.blend_mode) for i in images: painter.drawImage(0, 0, i) painter.end() self._image_item.setImage(rgb_view(result))
def drawMagnifierOnVideo(width, height, maskPixmap, dragPos, zoomPixmap, surface, painter, offset): ''' Draw Magnifier on Video ''' dim = min(width, height) MAX_MAGNIFIER = 229 magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3) radius = magnifierSize / 2 ring = radius - 15 box = QSize(magnifierSize, magnifierSize) # reupdate our mask if maskPixmap.size() != box: maskPixmap = QPixmap(box) maskPixmap.fill(Qt.transparent) g = QRadialGradient() g.setCenter(radius, radius) g.setFocalPoint(radius, radius) g.setRadius(radius) g.setColorAt(1.0, QColor(64, 64, 64, 0)) g.setColorAt(0.5, QColor(0, 0, 0, 255)) mask = QPainter(maskPixmap) mask.setRenderHint(QPainter.HighQualityAntialiasing) mask.setCompositionMode(QPainter.CompositionMode_Source) mask.setBrush(g) mask.setPen(Qt.NoPen) mask.drawRect(maskPixmap.rect()) mask.setBrush(QColor(Qt.transparent)) mask.drawEllipse(g.center(), ring, ring) mask.end() center = dragPos - QPoint(0, radius) center += QPoint(0, radius / 2) corner = center - QPoint(radius, radius) xy = center * 2 - QPoint(radius, radius) # only set the dimension to the magnified portion if zoomPixmap.size() != box: zoomPixmap = QPixmap(box) zoomPixmap.fill(Qt.lightGray) if True: painter_p = QPainter(zoomPixmap) painter_p.translate(-xy) largePixmap = QPixmap.fromImage(surface.image) painter_p.drawPixmap(offset, largePixmap) painter_p.end() clipPath = QPainterPath() clipPath.addEllipse(QPointF(center), ring, ring) painter.setClipPath(clipPath) painter.drawPixmap(corner, zoomPixmap) painter.setClipping(False) painter.drawPixmap(corner, maskPixmap) painter.setPen(Qt.gray) painter.drawPath(clipPath) return
def paintEvent(self, event): color = self.state_colors[self.state] painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) gradient = QLinearGradient(0, 0, self.width(), 0) gradient.setColorAt(0.0, Qt.transparent) gradient.setColorAt(1.0, color) painter.setBrush(QBrush(gradient)) gradient.setColorAt(1.0, color.stroke) painter.setPen(QPen(QBrush(gradient), 1)) painter.drawRoundedRect(-4, 0, self.width()+4, self.height(), 3.7, 3.7)
def paint(self, painter: QPainter) -> None: self.paint_text_items(painter) self.paint_thumbnail(painter) if self.hovering and self.animation_timer is None: if not self.fileinfo.isdir() and not self.fileinfo.is_archive(): painter.setCompositionMode(QPainter.CompositionMode_Overlay) painter.setOpacity(0.75) self.paint_thumbnail(painter) painter.setOpacity(1.0) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) if self.level_of_detail > 1: self.paint_metadata(painter) self.paint_overlay(painter)
def editPaste(self, pasting=False): """ Public slot to paste an image from the clipboard. @param pasting flag indicating part two of the paste operation (boolean) """ img, ok = self.__clipboardImage() if ok: if img.width() > self.__image.width() or \ img.height() > self.__image.height(): res = E5MessageBox.yesNo( self, self.tr("Paste"), self.tr( """<p>The clipboard image is larger than the""" """ current image.<br/>Paste as new image?</p>""")) if res: self.editPasteAsNew() return elif not pasting: self.__isPasting = True self.__clipboardSize = img.size() else: cmd = IconEditCommand(self, self.tr("Paste Clipboard"), self.__image) self.__markImage.fill(self.NoMarkColor.rgba()) painter = QPainter(self.__image) painter.setPen(self.penColor()) painter.setCompositionMode(self.__compositingMode) painter.drawImage( self.__pasteRect.x(), self.__pasteRect.y(), img, 0, 0, self.__pasteRect.width() + 1, self.__pasteRect.height() + 1) self.__undoStack.push(cmd) cmd.setAfterImage(self.__image) self.__updateImageRect( self.__pasteRect.topLeft(), self.__pasteRect.bottomRight() + QPoint(1, 1)) else: E5MessageBox.warning( self, self.tr("Pasting Image"), self.tr("""Invalid image data in clipboard."""))
def brushValuePixmap(b): img = QImage(16, 16, QImage.Format_ARGB32_Premultiplied) img.fill(0) painter = QPainter(img) #painter.begin() painter.setCompositionMode(QPainter.CompositionMode_Source) painter.fillRect(0, 0, img.width(), img.height(), b) color = b.color() if (color.alpha() != 255): # indicate alpha by an inset opaqueBrush = b color.setAlpha(255) opaqueBrush.setColor(color) painter.fillRect(img.width() / 4, img.height() / 4, img.width() / 2, img.height() / 2, opaqueBrush) painter.end() return QPixmap.fromImage(img)
def startDrag(self): image = self.image() data = QMimeData() data.setImageData(image) drag = QDrag(self) drag.setMimeData(data) if max(image.width(), image.height()) > 256: image = image.scaled(QSize(256, 256), Qt.KeepAspectRatio, Qt.SmoothTransformation) p = QPainter() p.begin(image) p.setCompositionMode(QPainter.CompositionMode_DestinationIn) p.fillRect(image.rect(), QColor(0, 0, 0, 160)) p.end() pixmap = QPixmap.fromImage(image) drag.setPixmap(pixmap) drag.setHotSpot(pixmap.rect().center()) drag.exec_(Qt.CopyAction)
def __grabRect(self): """ Private method to grab the selected rectangle (i.e. do the snapshot). """ if self.__mode == SnapshotRegionGrabber.Ellipse: ell = QRegion(self.__selection, QRegion.Ellipse) if not ell.isEmpty(): self.__grabbing = True xOffset = self.__pixmap.rect().x() - ell.boundingRect().x() yOffset = self.__pixmap.rect().y() - ell.boundingRect().y() translatedEll = ell.translated(xOffset, yOffset) pixmap2 = QPixmap(ell.boundingRect().size()) pixmap2.fill(Qt.transparent) pt = QPainter() pt.begin(pixmap2) if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff): pt.setRenderHints( QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform, True) pt.setBrush(Qt.black) pt.setPen(QPen(QBrush(Qt.black), 0.5)) pt.drawEllipse(translatedEll.boundingRect()) pt.setCompositionMode(QPainter.CompositionMode_SourceIn) else: pt.setClipRegion(translatedEll) pt.setCompositionMode(QPainter.CompositionMode_Source) pt.drawPixmap(pixmap2.rect(), self.__pixmap, ell.boundingRect()) pt.end() self.grabbed.emit(pixmap2) else: r = QRect(self.__selection) if not r.isNull() and r.isValid(): self.__grabbing = True self.grabbed.emit(self.__pixmap.copy(r))
def __setImagePixel(self, pos, opaque): """ Private slot to set or erase a pixel. @param pos position of the pixel in the widget (QPoint) @param opaque flag indicating a set operation (boolean) """ i, j = self.__imageCoordinates(pos) if self.__image.rect().contains(i, j) and (i, j) != self.__lastPos: if opaque: painter = QPainter(self.__image) painter.setPen(self.penColor()) painter.setCompositionMode(self.__compositingMode) painter.drawPoint(i, j) else: self.__image.setPixel(i, j, qRgba(0, 0, 0, 0)) self.__lastPos = (i, j) self.update(self.__pixelRect(i, j))
def __init__(self, parent=None, size=16): super(ClearButton, self).__init__(parent) self.setCursor(Qt.ArrowCursor) self.setFocusPolicy(Qt.NoFocus) self.setToolTip(u"Clear") self.setVisible(False) self.setMinimumSize(size+2, size+2) pixmap = QPixmap() if pixmap.load(Resources.get("icons/delete.svg")): self.icon = pixmap.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation) # Use QImage because QPainter using a QPixmap does not support CompositionMode_Multiply -Dan image = self.icon.toImage() painter = QPainter(image) painter.setRenderHint(QPainter.Antialiasing, True) painter.setCompositionMode(QPainter.CompositionMode_Multiply) painter.drawPixmap(0, 0, self.icon) painter.end() self.icon_pressed = QPixmap(image) else: self.icon = self.icon_pressed = None
def pixmap(self, mode=QIcon.Normal, state=QIcon.Off): pixmap = self.icon().pixmap(self.iconSize(), mode, state) if pixmap.isNull(): return pixmap size = max(pixmap.width(), pixmap.height()) offset_x = (size - pixmap.width()) / 2 offset_y = (size - pixmap.height()) / 2 new_pixmap = QPixmap(size, size) new_pixmap.fill(Qt.transparent) path = QPainterPath() path.addRoundedRect(0, 0, size, size, 3.7, 3.7) painter = QPainter(new_pixmap) painter.setRenderHint(QPainter.Antialiasing, True) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) painter.setClipPath(path) painter.drawPixmap(offset_x, offset_y, pixmap) painter.end() return new_pixmap
def mouseMoveEvent(self, event): if event.buttons() == Qt.RightButton: # write the relative cursor position to mime data mimeData = QMimeData() # simple string with 'x,y' mimeData.setText('%d,%d' % (event.x(), event.y())) # let's make it fancy. we'll show a "ghost" of the button as we drag # grab the button to a pixmap pixmap = self.grab() # below makes the pixmap half transparent painter = QPainter(pixmap) painter.setCompositionMode(painter.CompositionMode_DestinationIn) painter.fillRect(pixmap.rect(), QColor(0, 0, 0, 127)) painter.end() # make a QDrag drag = QDrag(self) # put our MimeData drag.setMimeData(mimeData) # set its Pixmap drag.setPixmap(pixmap) # shift the Pixmap so that it coincides with the cursor position drag.setHotSpot(event.pos()) # start the drag operation # exec_ will return the accepted action from dropEvent if drag.exec_(Qt.CopyAction | Qt.MoveAction) == Qt.MoveAction: print('moved') else: print('copied:'+str(event.globalPos())) #self.move(event.pos()) elif event.buttons() == Qt.LeftButton: delta = QPoint(event.globalPos() - self.oldPos) self.move(self.frameGeometry().x() + delta.x(), self.frameGeometry().y() + delta.y()) self.oldPos = event.globalPos()
def getRoundPixmap(self, pixmap): """pixmap原图""" resultImage = QImage(pixmap.size(), QImage.Format_ARGB32_Premultiplied) head_mask = QPixmap(os.path.join(Settings().dataDir, "images", "mask.png")) painter = QPainter(resultImage) painter.setCompositionMode(QPainter.CompositionMode_Source) painter.fillRect(resultImage.rect(), Qt.transparent) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) painter.drawPixmap(0, 0, head_mask) painter.setCompositionMode(QPainter.CompositionMode_SourceOut) painter.drawPixmap(0, 0, pixmap) painter.setCompositionMode(QPainter.CompositionMode_DestinationOver) painter.end() result = QPixmap.fromImage(resultImage) del resultImage, head_mask return result
def paintEvent(self, e): qp = QPainter() qp.begin(self) #self.drawWidget(qp) if self.selected: qp.setCompositionMode(QPainter.CompositionMode_HardLight) qp.setBrush(QColor(0, 0, 0, 128)) qp.drawRect(0,0, self.width(), self.height()) qp.setCompositionMode(QPainter.CompositionMode_Overlay) qp.setBrush(QColor(255, 255, 255, 255)) width = self.last_position.x() - self.start_position.x() height = self.last_position.y()-self.start_position.y() qp.drawRect(self.start_position.x(), self.start_position.y(), width, height) qp.setCompositionMode(QPainter.CompositionMode_SourceOver) image_w = min([abs(width), abs(height), self.crop.width()]) #self.crop.width() image_h = image_w #self.crop.height() qp.drawPixmap(self.start_position.x() + width/2 - image_w/2, self.start_position.y() + height/2 - image_h/2, image_w, image_h, self.crop) qp.end()
def colorifyPixmap(pixmap, color): # FIXME: ugly p = QPainter(pixmap) p.setCompositionMode(p.CompositionMode_Overlay) p.fillRect(pixmap.rect(), color) return pixmap
def __drawTool(self, pos, mark): """ Private method to perform a draw operation depending of the current tool. @param pos widget coordinate to perform the draw operation at (QPoint) @param mark flag indicating a mark operation (boolean) @return flag indicating a successful draw (boolean) """ self.__unMark() if mark: self.__endPos = QPoint(pos) drawColor = self.MarkColor img = self.__markImage else: drawColor = self.penColor() img = self.__image start = QPoint(*self.__imageCoordinates(self.__startPos)) end = QPoint(*self.__imageCoordinates(pos)) painter = QPainter(img) painter.setPen(drawColor) painter.setCompositionMode(self.__compositingMode) if self.__curTool == self.Line: painter.drawLine(start, end) elif self.__curTool in [self.Rectangle, self.FilledRectangle, self.RectangleSelection]: left = min(start.x(), end.x()) top = min(start.y(), end.y()) right = max(start.x(), end.x()) bottom = max(start.y(), end.y()) if self.__curTool == self.RectangleSelection: painter.setBrush(QBrush(drawColor)) if self.__curTool == self.FilledRectangle: for y in range(top, bottom + 1): painter.drawLine(left, y, right, y) else: painter.drawRect(left, top, right - left, bottom - top) if self.__selecting: self.__selRect = QRect( left, top, right - left + 1, bottom - top + 1) self.__selectionAvailable = True self.selectionAvailable.emit(True) elif self.__curTool in [self.Circle, self.FilledCircle, self.CircleSelection]: r = max(abs(start.x() - end.x()), abs(start.y() - end.y())) if self.__curTool in [self.FilledCircle, self.CircleSelection]: painter.setBrush(QBrush(drawColor)) painter.drawEllipse(start, r, r) if self.__selecting: self.__selRect = QRect(start.x() - r, start.y() - r, 2 * r + 1, 2 * r + 1) self.__selectionAvailable = True self.selectionAvailable.emit(True) elif self.__curTool in [self.Ellipse, self.FilledEllipse]: r1 = abs(start.x() - end.x()) r2 = abs(start.y() - end.y()) if r1 == 0 or r2 == 0: return False if self.__curTool == self.FilledEllipse: painter.setBrush(QBrush(drawColor)) painter.drawEllipse(start, r1, r2) painter.end() if self.__curTool in [self.Circle, self.FilledCircle, self.Ellipse, self.FilledEllipse]: self.update() else: self.__updateRect(self.__startPos, pos) return True
def draw_icon(icon, rect, painter, icon_mode, shadow=False): cache = icon.pixmap(rect.size()) dip_offset = QPoint(1, -2) cache = QPixmap() pixname = "icon {0} {1} {2}".format( icon.cacheKey(), icon_mode, rect.height() ) if QPixmapCache.find(pixname) is None: pix = icon.pixmap(rect.size()) device_pixel_ratio = pix.devicePixelRatio() radius = 3 * device_pixel_ratio offset = dip_offset * device_pixel_ratio cache = QPixmap(pix.size() + QSize(radius * 2, radius * 2)) cache.fill(Qt.transparent) cache_painter = QPainter(cache) if icon_mode == QIcon.Disabled: im = pix.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(0, im.height()): scanline = im.scanLine(y) for x in range(0, im.width()): pixel = scanline intensity = qGray(pixel) scanline = qRgba( intensity, intensity, intensity, qAlpha(pixel)) scanline += 1 pix = QPixmap.fromImage(im) # Draw shadow tmp = QImage(pix.size() + QSize(radius * 2, radius * 2), QImage.Format_ARGB32_Premultiplied) tmp.fill(Qt.transparent) tmp_painter = QPainter(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_Source) tmp_painter.drawPixmap( QRect(radius, radius, pix.width(), pix.height()), pix) tmp_painter.end() # Blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blur_painter = QPainter(blurred) blur_painter.end() # tmp = blurred tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() tmp_painter.begin(tmp) tmp_painter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmp_painter.fillRect(tmp.rect(), QColor(0, 0, 0, 150)) tmp_painter.end() # Draw the blurred drop shadow cache_painter.drawImage( QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp) # Draw the actual pixmap cache_painter.drawPixmap( QRect(QPoint(radius, radius) + offset, QSize(pix.width(), pix.height())), pix) cache_painter.end() cache.setDevicePixelRatio(device_pixel_ratio) QPixmapCache.insert(pixname, cache) target_rect = cache.rect() target_rect.setSize(target_rect.size() / cache.devicePixelRatio()) target_rect.moveCenter(rect.center() - dip_offset) painter.drawPixmap(target_rect, cache)
def paintEvent(self, event): p = QPainter() p.begin(self) self._normalMap.render(p, event.rect()) p.setPen(Qt.black) p.drawText(self.rect(), Qt.AlignBottom | Qt.TextWordWrap, "Map data CCBYSA 2009 OpenStreetMap.org contributors") p.end() if self.zoomed: dim = min(self.width(), self.height()) magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3) radius = magnifierSize / 2 ring = radius - 15 box = QSize(magnifierSize, magnifierSize) # reupdate our mask if self.maskPixmap.size() != box: self.maskPixmap = QPixmap(box) self.maskPixmap.fill(Qt.transparent) g = QRadialGradient() g.setCenter(radius, radius) g.setFocalPoint(radius, radius) g.setRadius(radius) g.setColorAt(1.0, QColor(255, 255, 255, 0)) g.setColorAt(0.5, QColor(128, 128, 128, 255)) mask = QPainter(self.maskPixmap) mask.setRenderHint(QPainter.Antialiasing) mask.setCompositionMode(QPainter.CompositionMode_Source) mask.setBrush(g) mask.setPen(Qt.NoPen) mask.drawRect(self.maskPixmap.rect()) mask.setBrush(QColor(Qt.transparent)) mask.drawEllipse(g.center(), ring, ring) mask.end() center = self.dragPos - QPoint(0, radius) center += QPoint(0, radius / 2) corner = center - QPoint(radius, radius) xy = center * 2 - QPoint(radius, radius) # only set the dimension to the magnified portion if self.zoomPixmap.size() != box: self.zoomPixmap = QPixmap(box) self.zoomPixmap.fill(Qt.lightGray) if True: p = QPainter(self.zoomPixmap) p.translate(-xy) self._largeMap.render(p, QRect(xy, box)) p.end() clipPath = QPainterPath() clipPath.addEllipse(QPointF(center), ring, ring) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) p.setClipPath(clipPath) p.drawPixmap(corner, self.zoomPixmap) p.setClipping(False) p.drawPixmap(corner, self.maskPixmap) p.setPen(Qt.gray) p.drawPath(clipPath) if self.invert: p = QPainter(self) p.setCompositionMode(QPainter.CompositionMode_Difference) p.fillRect(event.rect(), Qt.white) p.end()