def add_v_gradient(image, colors): if len(colors) < 2: return image new_img = image.copy() if not new_img.format() is QImage.Format_ARGB32_Premultiplied: new_img = new_img.convertToFormat(QImage.Format_ARGB32_Premultiplied) gradient = QtGui.QLinearGradient(0, 0, 0, new_img.height()) gradient.setColorAt(0, colors[0]) for i in range(1, len(colors) - 1): gradient.setColorAt(i / len(colors), colors[i]) gradient.setColorAt(1, colors[-1]) painter = QPainter(new_img) painter.setCompositionMode(QPainter.CompositionMode_SourceAtop) painter.fillRect(new_img.rect(), gradient) painter.end() return new_img
def add_piece_func(o, piece_id, mask_image, offset): # o.source_image required (QImage) L.debug('add_piece_func %d %r' % (piece_id, offset)) pieceImage = QImage(mask_image) piecePainter = QPainter(pieceImage) piecePainter.setCompositionMode(QPainter.CompositionMode_SourceIn) piecePainter.drawImage( QPoint(), _safeQImageCopy(o.source_image, QRect(offset, mask_image.size()))) piecePainter.end() # save pieceImage as pieces/piece<id>.png imgfile = 'piece%d.png' % piece_id pieceImage.save(os.path.join(o.board.imagefolder, imgfile)) dominant_colors = find_colors(pieceImage) # add piece to puzzleboard o.board.pieces.append( Piece( id=piece_id, image=imgfile, x0=offset.x(), y0=offset.y(), w=pieceImage.width(), h=pieceImage.height(), dominant_colors=dominant_colors, ))
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 updateTerritoryOwner(self, name, owner): t = self.game.board.getTerritory(name) p = self.game.getPlayer(owner) color = QColor(*p.color) color.setAlpha(200) territoryImage = QImage(t.image.size(), QImage.Format_ARGB32_Premultiplied) p = QPainter() p.begin(territoryImage) p.drawImage(0, 0, self.game.board.image) p.setCompositionMode(QPainter.CompositionMode_DestinationIn) p.drawImage(0, 0, t.image) p.end() coloredTerritoryImage = QImage(territoryImage.size(), QImage.Format_ARGB32_Premultiplied) coloredTerritoryImage.fill(0) p.begin(coloredTerritoryImage) p.fillRect(territoryImage.rect(), color) p.setCompositionMode(QPainter.CompositionMode_DestinationIn) p.drawImage(0, 0, t.image) p.end() p.begin(self.ownershipMap) p.drawImage(0, 0, territoryImage) p.drawImage(0, 0, coloredTerritoryImage) p.end() self.scaledOwnershipMap = self.ownershipMap.scaled(self.imageSize()) self.update()
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 createOnlineIcon(self,color): dim = QRect(0,0,32,32) img = QImage(dim.size(),QImage.Format_ARGB32) p = QPainter(img) p.setCompositionMode(QPainter.CompositionMode_Source) p.fillRect(dim,Qt.transparent) p.setCompositionMode(QPainter.CompositionMode_SourceOver) p.setRenderHints(QPainter.Antialiasing) p.setPen(Qt.black) p.setBrush(color) p.drawEllipse(dim.adjusted(1,1,-2,-2)) return img
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 createOnlineIcon(self, color): dim = QRect(0, 0, 32, 32) img = QImage(dim.size(), QImage.Format_ARGB32) p = QPainter(img) p.setCompositionMode(QPainter.CompositionMode_Source) p.fillRect(dim, Qt.transparent) p.setCompositionMode(QPainter.CompositionMode_SourceOver) p.setRenderHints(QPainter.Antialiasing) p.setPen(Qt.black) p.setBrush(color) p.drawEllipse(dim.adjusted(1, 1, -2, -2)) return img
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 replace_all_colors(image, color): new_img = image.copy() if not new_img.format() is QImage.Format_ARGB32_Premultiplied: new_img = new_img.convertToFormat(QImage.Format_ARGB32_Premultiplied) color_img = QImage(new_img.width(), new_img.height(), QImage.Format_ARGB32_Premultiplied) color_img.fill(color.rgba()) painter = QPainter(new_img) painter.setCompositionMode(QPainter.CompositionMode_SourceAtop) painter.drawImage(new_img.rect(), color_img, color_img.rect()) painter.end() return new_img
def set_user_icon(self, image_file_name): pixmap = QPixmap(32, 32) pixmap.fill(QColor(Qt.transparent)) painter = QPainter(pixmap) painter.setRenderHint(QPainter.Antialiasing, True) painter.setBrush(QBrush(Qt.white)) painter.setPen(QPen(painter.brush(), 0, Qt.NoPen)) #painter.drawRoundedRect(0, 0, 32, 32, 6, 6) painter.drawRoundedRect(0, 0, 32, 32, 0, 0) icon = QPixmap() if icon.load(image_file_name): icon = icon.scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) painter.drawPixmap(0, 0, icon) painter.end() self.image.setPixmap(pixmap)
def render(self,fname): contentsSize = self.contentFrame.contentsSize() contentsSize -= QSize(self.m_scrollPosition.x(), self.m_scrollPosition.y()) frameRect = QRect(QPoint(0, 0), contentsSize) #if not self.m_clipRect.isEmpty(): # frameRect = self.m_clipRect viewportSize = self.contentPage.viewportSize() self.contentPage.setViewportSize(contentsSize) image = QImage(frameRect.size(), QImage.Format_ARGB32) image.fill(qRgba(255, 255, 255, 0)) painter = QPainter() # We use tiling approach to work-around Qt software rasterizer bug # when dealing with very large paint device. # See http://code.google.com/p/phantomjs/issues/detail?id=54. tileSize = 4096 htiles = (image.width() + tileSize - 1) / tileSize vtiles = (image.height() + tileSize - 1) / tileSize for x in range(htiles): for y in range(vtiles): tileBuffer = QImage(tileSize, tileSize, QImage.Format_ARGB32) tileBuffer.fill(qRgba(255, 255, 255, 0)) # Render the web page onto the small tile first painter.begin(tileBuffer) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) painter.translate(-frameRect.left(), -frameRect.top()) painter.translate(-x * tileSize, -y * tileSize) self.contentFrame.render(painter, QRegion(frameRect)) painter.end() # Copy the tile to the main buffer painter.begin(image) painter.setCompositionMode(QPainter.CompositionMode_Source) painter.drawImage(x * tileSize, y * tileSize, tileBuffer) painter.end() self.contentPage.setViewportSize(viewportSize) image.save(fname) return True
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 renderImage(self): contentsSize = self.m_mainFrame.contentsSize() contentsSize -= QSize(self.m_scrollPosition.x(), self.m_scrollPosition.y()) frameRect = QRect(QPoint(0, 0), contentsSize) if not self.m_clipRect.isEmpty(): frameRect = self.m_clipRect viewportSize = self.m_webPage.viewportSize() self.m_webPage.setViewportSize(contentsSize) image = QImage(frameRect.size(), QImage.Format_ARGB32) image.fill(qRgba(255, 255, 255, 0)) painter = QPainter() # We use tiling approach to work-around Qt software rasterizer bug # when dealing with very large paint device. # See http://code.google.com/p/phantomjs/issues/detail?id=54. tileSize = 4096 htiles = (image.width() + tileSize - 1) / tileSize vtiles = (image.height() + tileSize - 1) / tileSize for x in range(htiles): for y in range(vtiles): tileBuffer = QImage(tileSize, tileSize, QImage.Format_ARGB32) tileBuffer.fill(qRgba(255, 255, 255, 0)) # Render the web page onto the small tile first painter.begin(tileBuffer) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHint(QPainter.TextAntialiasing, True) painter.setRenderHint(QPainter.SmoothPixmapTransform, True) painter.translate(-frameRect.left(), -frameRect.top()) painter.translate(-x * tileSize, -y * tileSize) self.m_mainFrame.render(painter, QRegion(frameRect)) painter.end() # Copy the tile to the main buffer painter.begin(image) painter.setCompositionMode(QPainter.CompositionMode_Source) painter.drawImage(x * tileSize, y * tileSize, tileBuffer) painter.end() self.m_webPage.setViewportSize(viewportSize) return image
def coloredMask(self, territory, color): pixmap = self.coloredMaskCache.get(territory, color) if not pixmap: mask = self.masks[territory] size = self.imageSize() rect = self.imageRect() image = QImage(size, QImage.Format_ARGB32_Premultiplied) image.fill(0) painter = QPainter() painter.begin(image) painter.setCompositionMode(QPainter.CompositionMode_Source) color.setAlpha(100) painter.fillRect(rect, color) painter.setCompositionMode(QPainter.CompositionMode_DestinationIn) painter.drawImage(0, 0, mask) painter.end() pixmap = QPixmap.fromImage(image) self.coloredMaskCache.set(territory, color, pixmap) return pixmap
def generate_preview(o): size = o.ui.previewImage.size() img = QImage(size, QImage.Format_ARGB32) img.fill(QColor(224, 224, 224, 255)) painter = QPainter(img) painter.setCompositionMode(QPainter.CompositionMode_SourceOver) def preview_add_piece_func(piece_id, mask_image, offset): painter.drawImage(offset, mask_image) engine = GoldbergEngine(preview_add_piece_func, lambda id1, id2: None, o.settings, outline_only=True) engine(o._cur_grid_generator().generate_grid, 30, size.width(), size.height()) painter.end() o.ui.previewImage.setPixmap(QPixmap(img))
def __init__(self, parent=None, size=16): QAbstractButton.__init__(self, 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 tintImage(cls, img, tintColor): """ :type img: QImage :type tintColor: QColor """ p = QPainter(img) p.setCompositionMode(QPainter.CompositionMode_Screen) for x in range(0, img.width()): for y in range(0, img.height()): rgbColor = img.pixel(x, y) alpha = qAlpha(rgbColor) c = QColor(rgbColor) if alpha > 0: c.toHsl() l = c.lightnessF()() newColor = QColor.fromHslF(tintColor.hslHueF(), tintColor.hslSaturationF(), l) newColor.setAlpha(alpha) img.setPixel(x, y, newColor.rgba())
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 __init__(self, parent=None, size=16): QAbstractButton.__init__(self, 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 getProtoStatusIcon(name, proto_int=None): """Creates a nice little overlay of the status and the protocol icon. Returns QIcon""" status_icon = getIcon(name) if not proto_int: return status_icon else: ret = _status_icon_cache.get((name, proto_int), None) if ret: return ret proto_name, _ = proto_name_int(proto_int, _PROTO_INT) status_pixmap = status_icon.pixmap(QSize(16,16)) proto_pixmap = getIcon(proto_name).pixmap(QSize(16,16)) combined_pixmap = QImage(28,20, QImage.Format_ARGB32_Premultiplied) painter = QPainter(combined_pixmap) painter.setCompositionMode(painter.CompositionMode_Source) painter.fillRect(combined_pixmap.rect(), Qt.transparent) painter.setCompositionMode(painter.CompositionMode_Source) painter.drawPixmap(QPoint(0,0), status_pixmap) painter.setCompositionMode(painter.CompositionMode_SourceOver) painter.drawPixmap(QPoint(12,4), proto_pixmap) painter.end() #add cache _status_icon_cache[(name, proto_int)] = QIcon(QPixmap.fromImage(combined_pixmap)) return _status_icon_cache[(name, proto_int)]
def mouseMoveEvent(self, e): # Chequear que se esté presionando el botón izquierdo if e.buttons() != Qt.LeftButton: return # posicion del click dentro del gmod mimeData = QMimeData() pixmap = QPixmap.grabWidget(self) painter = QPainter(pixmap) painter.setCompositionMode(painter.CompositionMode_DestinationIn) painter.fillRect(pixmap.rect(), QColor(0, 0, 0, 127)) painter.end() drag = QDrag(self) # escribir el MimeData drag.setMimeData(mimeData) # establecer el Pixmap drag.setPixmap(pixmap) # posicionar correctamente el pixmap drag.setHotSpot(e.pos()) drag.exec_(Qt.MoveAction)
def lightening(image, lighten=False, **kwargs): """ Appliquer un filtre lumineux sur l'image. L'éclairage est obtenu en mode de composition PLUS, avec une lumière de couleur légèrement jaune. :param image: image PIL :param lighten: False ou un float entre 0.0 (identité) et 1.0 (lumière max) """ try: lighten_ = float(lighten) except ValueError: lighten_ = 0 if lighten_ > 0: qimage = _pil_to_qt(image) painter = QPainter(qimage) painter.setCompositionMode(QPainter.CompositionMode_Plus) painter.fillRect(0, 0, qimage.width(), qimage.height(), QColor(255, 217, 161, lighten_ * 255.0)) painter.end() return _qt_to_pil(qimage) else: return image
def drawIconWithShadow(cls, icon, rect, painter, iconMode, dipRadius=3, color=QColor(0, 0, 0, 130), dipOffset=QPoint(1, -2)): """ :type icon: QIcon :type rect: QRect :type painter: QPainter :type iconMode: QIcon.Mode :type dipRadius: int :type color: QColor :type dipOffset: QPoint """ cache = QPixmap() pixmapName = "icon {0} {1} {2}".format(icon.cacheKey(), iconMode, rect.height()) if not QPixmapCache.find(pixmapName, cache): # High-dpi support: The in parameters (rect, radius, offset) are in # device-independent pixels. The call to QIcon.pixmap() below might # return a high-dpi pixmap, which will in that case have a devicePixelRatio # different than 1. The shadow drawing calculations are done in device # pixels. from math import ceil px = icon.pixmap(rect.size()) devicePixelRatio = int(ceil(cls.pixmapDevicePixelRatio(px))) radius = dipRadius * devicePixelRatio offset = dipOffset * devicePixelRatio # result = QPoint, like dipOffset cache = QPixmap(px.size() + QSize(radius * 2, radius * 2)) cache.fill(Qt.transparent) cachePainter = QPainter(cache) if iconMode == QIcon.Disabled: im = px.toImage().convertToFormat(QImage.Format_ARGB32) for y in range(0, im.height()): scanLine = abs(im.scanLine(y)) for x in range(0, im.width()): pixel = scanLine intensity = qGray(pixel) scanLine = qRgba(intensity, intensity, intensity, qAlpha(pixel)) scanLine += 1 px = QPixmap.fromImage(im) # Draw shadow tmp = QImage(px.size() + QSize(radius * 2, radius * 2 + 1), QImage.Format_ARGB32_Premultiplied) tmp.fill(Qt.transparent) tmpPainter = QPainter(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_Source) tmpPainter.drawPixmap(QRect(radius, radius, px.width(), px.height()), px) tmpPainter.end() # blur the alpha channel blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied) blurred.fill(Qt.transparent) blurPainter = QPainter(blurred) # qt_blurImage is not available in PyQt4, skip it # qt_blurImage(&blurPainter, tmp, radius, false, true) blurPainter.end() tmp = blurred # blacken the image... tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() tmpPainter.begin(tmp) tmpPainter.setCompositionMode(QPainter.CompositionMode_SourceIn) tmpPainter.fillRect(tmp.rect(), color) tmpPainter.end() # draw the blurred drop shadow... cachePainter.drawImage(QRect(0, 0, cache.rect().width(), cache.rect().height()), tmp) # Draw the actual pixmap... cachePainter.drawPixmap(QRect(QPoint(radius, radius) + offset, QSize(px.width(), px.height())), px) import PyQt4 if StrictVersion(PyQt4.QtCore.__version__).version[0] == 5: cache.setDevicePixelRatio(devicePixelRatio) QPixmapCache.insert(pixmapName, cache) targetRect = cache.rect() targetRect.setSize(targetRect.size() / cls.pixmapDevicePixelRatio(cache)) targetRect.moveCenter(rect.center() - dipOffset) painter.drawPixmap(targetRect, cache)
def draw_scene(scene_info, text=None): bg = None max_length = 0 kill_blanks = False if scene_info.mode in [ common.SCENE_MODES.normal, common.SCENE_MODES.normal_flat ]: bg = get_normal(scene_info) if scene_info.box_type == common.BOX_TYPES.flat: scene_info.mode = common.SCENE_MODES.normal_flat else: scene_info.mode = common.SCENE_MODES.normal elif scene_info.mode == common.SCENE_MODES.trial: bg = get_trial(scene_info) elif scene_info.mode == common.SCENE_MODES.novel: scene_info.box_type = common.BOX_TYPES.novel bg = get_normal(scene_info) elif scene_info.mode == common.SCENE_MODES.rules: bg = QImage(os.path.join(MENU_DIR, "rules.png")) elif scene_info.mode == common.SCENE_MODES.ammo: bg = QImage(os.path.join(MENU_DIR, "ammo-desc.png")) overlay = get_ammo(scene_info.file_id, 254, 117) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.setCompositionMode(QPainter.CompositionMode_DestinationOver) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() name = get_ammo_name(scene_info.file_id) if name: bg = print_text(bg, name, common.SCENE_MODES.ammoname, TEXT_FORMATS[common.SCENE_MODES.ammoname], False) elif scene_info.mode == common.SCENE_MODES.ammoname: bg = QImage(os.path.join(MENU_DIR, "ammo-list.png")) overlay = get_ammo(scene_info.file_id, 254, 61) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.setCompositionMode(QPainter.CompositionMode_DestinationOver) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() elif scene_info.mode == common.SCENE_MODES.present: bg = QImage(os.path.join(MENU_DIR, "present-desc.png")) overlay = get_present(scene_info.file_id, 248, 96) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() name = get_present_name(scene_info.file_id) if name: bg = print_text(bg, name, common.SCENE_MODES.presentname, TEXT_FORMATS[common.SCENE_MODES.presentname], False) elif scene_info.mode == common.SCENE_MODES.presentname: bg = QImage(os.path.join(MENU_DIR, "present-list.png")) overlay = get_present(scene_info.file_id, 248, 46) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() elif scene_info.mode == common.SCENE_MODES.menu: bg = QImage(os.path.join(MENU_DIR, "menu.png")) elif scene_info.mode == common.SCENE_MODES.report or scene_info.mode == common.SCENE_MODES.report2: bg = QImage(os.path.join(MENU_DIR, "report.png")) elif scene_info.mode == common.SCENE_MODES.skill or scene_info.mode == common.SCENE_MODES.skill2: bg = QImage(os.path.join(MENU_DIR, "skills.png")) elif scene_info.mode == common.SCENE_MODES.map: bg = QImage(os.path.join(MENU_DIR, "map.png")) elif scene_info.mode == common.SCENE_MODES.music: bg = QImage(os.path.join(MENU_DIR, "soundtest.png")) elif scene_info.mode in [ common.SCENE_MODES.eventname, common.SCENE_MODES.moviename, common.SCENE_MODES.artworkname ]: bg = QImage(os.path.join(MENU_DIR, "gallery.png")) if scene_info.mode == common.SCENE_MODES.eventname: overlay = get_event_icon(scene_info.file_id) elif scene_info.mode == common.SCENE_MODES.moviename: overlay = get_movie_icon(scene_info.file_id) elif scene_info.mode == common.SCENE_MODES.artworkname: overlay = get_artwork_icon(scene_info.file_id) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() elif scene_info.mode == common.SCENE_MODES.theatre: bg = get_normal(scene_info) elif scene_info.mode == common.SCENE_MODES.debate or scene_info.mode == common.SCENE_MODES.hanron: bg = get_trial(scene_info, show_box=False) else: bg = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) bg.fill(QColor(0, 0, 0, 255).rgba()) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) if scene_info.cutin != -1: cutin = get_cutin(scene_info.cutin) painter = QPainter(bg) painter.drawImage(bg.rect(), cutin, cutin.rect()) painter.end() if scene_info.ammo != -1: ammo = get_ammo_ingame(scene_info.ammo) painter = QPainter(bg) painter.drawImage(bg.rect(), ammo, ammo.rect()) painter.end() if scene_info.present != -1: present = get_present_ingame(scene_info.present) painter = QPainter(bg) painter.drawImage(bg.rect(), present, present.rect()) painter.end() if scene_info.special == common.SCENE_SPECIAL.option: overlay = QImage(os.path.join(TEXTBOX_DIR, "option_bar.png")) painter = QPainter(bg) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() if not text == None and not text == "": bg = print_text(bg, text, common.SCENE_SPECIAL.option, TEXT_FORMATS[common.SCENE_SPECIAL.option], False) if not text == None and not text == "": bg = print_text(bg, text, scene_info.mode, TEXT_FORMATS[scene_info.mode]) return bg
def draw_scene(scene_info, text = None): bg = None max_length = 0 kill_blanks = False if scene_info.mode in [common.SCENE_MODES.normal, common.SCENE_MODES.normal_flat]: bg = get_normal(scene_info) if scene_info.box_type == common.BOX_TYPES.flat: scene_info.mode = common.SCENE_MODES.normal_flat else: scene_info.mode = common.SCENE_MODES.normal elif scene_info.mode == common.SCENE_MODES.trial: bg = get_trial(scene_info) elif scene_info.mode == common.SCENE_MODES.novel: scene_info.box_type = common.BOX_TYPES.novel bg = get_normal(scene_info) elif scene_info.mode == common.SCENE_MODES.rules: bg = QImage(os.path.join(MENU_DIR, "rules.png")) elif scene_info.mode == common.SCENE_MODES.ammo: bg = QImage(os.path.join(MENU_DIR, "ammo-desc.png")) overlay = get_ammo(scene_info.file_id, 254, 117) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.setCompositionMode(QPainter.CompositionMode_DestinationOver) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() name = get_ammo_name(scene_info.file_id) if name: bg = print_text(bg, name, common.SCENE_MODES.ammoname, TEXT_FORMATS[common.SCENE_MODES.ammoname], False) elif scene_info.mode == common.SCENE_MODES.ammoname: bg = QImage(os.path.join(MENU_DIR, "ammo-list.png")) overlay = get_ammo(scene_info.file_id, 254, 61) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.setCompositionMode(QPainter.CompositionMode_DestinationOver) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() elif scene_info.mode == common.SCENE_MODES.present: bg = QImage(os.path.join(MENU_DIR, "present-desc.png")) overlay = get_present(scene_info.file_id, 248, 96) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() name = get_present_name(scene_info.file_id) if name: bg = print_text(bg, name, common.SCENE_MODES.presentname, TEXT_FORMATS[common.SCENE_MODES.presentname], False) elif scene_info.mode == common.SCENE_MODES.presentname: bg = QImage(os.path.join(MENU_DIR, "present-list.png")) overlay = get_present(scene_info.file_id, 248, 46) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() elif scene_info.mode == common.SCENE_MODES.menu: bg = QImage(os.path.join(MENU_DIR, "menu.png")) elif scene_info.mode == common.SCENE_MODES.report or scene_info.mode == common.SCENE_MODES.report2: bg = QImage(os.path.join(MENU_DIR, "report.png")) elif scene_info.mode == common.SCENE_MODES.skill or scene_info.mode == common.SCENE_MODES.skill2: bg = QImage(os.path.join(MENU_DIR, "skills.png")) elif scene_info.mode == common.SCENE_MODES.map: bg = QImage(os.path.join(MENU_DIR, "map.png")) elif scene_info.mode == common.SCENE_MODES.music: bg = QImage(os.path.join(MENU_DIR, "soundtest.png")) elif scene_info.mode in [common.SCENE_MODES.eventname, common.SCENE_MODES.moviename, common.SCENE_MODES.artworkname]: bg = QImage(os.path.join(MENU_DIR, "gallery.png")) if scene_info.mode == common.SCENE_MODES.eventname: overlay = get_event_icon(scene_info.file_id) elif scene_info.mode == common.SCENE_MODES.moviename: overlay = get_movie_icon(scene_info.file_id) elif scene_info.mode == common.SCENE_MODES.artworkname: overlay = get_artwork_icon(scene_info.file_id) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) painter = QPainter(bg) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() elif scene_info.mode == common.SCENE_MODES.theatre: bg = get_normal(scene_info) elif scene_info.mode == common.SCENE_MODES.debate or scene_info.mode == common.SCENE_MODES.hanron: bg = get_trial(scene_info, show_box = False) else: bg = QImage(IMG_W, IMG_H, QImage.Format_ARGB32_Premultiplied) bg.fill(QColor(0, 0, 0, 255).rgba()) if not bg.format() is QImage.Format_ARGB32_Premultiplied: bg = bg.convertToFormat(QImage.Format_ARGB32_Premultiplied) if scene_info.cutin != -1: cutin = get_cutin(scene_info.cutin) painter = QPainter(bg) painter.drawImage(bg.rect(), cutin, cutin.rect()) painter.end() if scene_info.ammo != -1: ammo = get_ammo_ingame(scene_info.ammo) painter = QPainter(bg) painter.drawImage(bg.rect(), ammo, ammo.rect()) painter.end() if scene_info.present != -1: present = get_present_ingame(scene_info.present) painter = QPainter(bg) painter.drawImage(bg.rect(), present, present.rect()) painter.end() if scene_info.special == common.SCENE_SPECIAL.option: overlay = QImage(os.path.join(TEXTBOX_DIR, "option_bar.png")) painter = QPainter(bg) painter.drawImage(bg.rect(), overlay, overlay.rect()) painter.end() if not text == None and not text == "": bg = print_text(bg, text, common.SCENE_SPECIAL.option, TEXT_FORMATS[common.SCENE_SPECIAL.option], False) if not text == None and not text == "": bg = print_text(bg, text, scene_info.mode, TEXT_FORMATS[scene_info.mode]) return bg
def print_text(image, text, scene_mode = common.SCENE_MODES.normal, mangle = True): # A couple exceptions. if scene_mode in [common.SCENE_MODES.ammo, common.SCENE_MODES.present]: text_lines = text.split('\n') temp_text = text_lines[:2] temp_text = '\n'.join(temp_text) if len(text_lines) > 2: temp_text += "..." image = print_text(image, temp_text, common.SCENE_MODES.ammosummary, mangle) #default_clt = 0 format = TEXT_FORMAT[scene_mode] # Replace our unmarked CLTs with whatever default CLT we're given. # Also start the line off with the default CLT so we're definitely using it. # Useful for modes like Nonstop Debate, where text is normally CLT 16. text = "<CLT>" + text text = re.sub("<CLT>", "<CLT %d>" % format["clt"], text) img_w = IMG_W img_h = IMG_H if image: img_w = image.width() img_h = image.height() out = QImage(img_w, img_h, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) # This is a better representation of how the game handles text. painter.setCompositionMode(QPainter.CompositionMode_DestinationOver) painter.setRenderHint(QPainter.Antialiasing, True) split_text = text.split("\n") lines = [] lengths = [] clt_changes = [] last_clt = format["clt"] for line in split_text: # Start the line off with the last-used CLT, so the parsers know what it is. line = ("<CLT %d>" % last_clt) + line line, length, clt = font_parser.get_len(line, format["clt"]) # If there isn't an initial CLT, start the line off with # the CLT still in use at the end of the previous line. if not 0 in clt.keys(): clt[0] = last_clt last_clt = clt[max(clt.keys())] # If we're supposed to skip blanks and this line is blank # after parsing the formatting, then don't add it to the list. if format["killblanks"] and line.strip() == "": continue lines.append(line) lengths.append(length) clt_changes.append(clt) base_x = format["x"] base_y = format["y"] line_height = format["h"] x, y = base_x, base_y cur_clt = 0 cur_font = 1 cur_hscale = 1.0 cur_vscale = 1.0 if len(lines) == 0: text_height = 0 else: text_height = ((len(lines) - 1) * line_height) + 25 while text_height + y > IMG_H: y -= line_height #if y < 0: #y = 0 #break center_x = format["x"] + (format["w"] / 2.0) right_x = format["x"] + format["w"] for i in range(len(lines)): line = lines[i] # Only bother if we actually see the line. if y > -line_height and y < img_h: # Hack the line up a bit to reflect how it'll show up in-game # based on some in-game quirks. if mangle: line, lengths = mangle_line(line, lengths, i, scene_mode, cur_font, format["clt"]) line_length = sum(lengths[i]) if format["a"] == TEXT_ALIGN.left: x = base_x elif format["a"] == TEXT_ALIGN.right: x = right_x - line_length elif format["a"] == TEXT_ALIGN.center: x = center_x - (line_length / 2.0) elif format["a"] == TEXT_ALIGN.offcenter: x = center_x - (line_length / 2.0) - 7 # This is hackish as hell, but I want guidelines. # painter.end() # stripped_len = line_length # Strip the widths of any leading and trailing spaces # for j in range(len(line)): # if line[j] == ' ' or line[j] == u' ': # stripped_len -= lengths[i][j] # else: # break # for j in reversed(range(len(line))): # if line[j] == ' ' or line[j] == u' ': # stripped_len -= lengths[i][j] # else: # break # out = draw_centering_guides(out, center_x, y, stripped_len, 40) # painter = QPainter(out) # painter.setCompositionMode(QPainter.CompositionMode_DestinationOver) # painter.setRenderHint(QPainter.Antialiasing, True) # if format["a"] == blah for j in range(len(line)): char = line[j] if j in clt_changes[i]: cur_clt = clt_changes[i][j] letter, (xshift, yshift, final_w, final_h) = get_letter(cur_clt, char) final_x = (x + xshift) final_y = (y + yshift) + max(0, (line_height - final_h)) + CLT[cur_clt]['yshift'] # kind of hackish, lol, but the debate text # is centered vertically per line as well. if scene_mode == common.SCENE_MODES.debate: final_y -= (26 - final_h) / 2 painter.drawImage(QRect(final_x, final_y, final_w, final_h), letter, letter.rect()) x += lengths[i][j]# + CLT[cur_clt]['xshift'] # for j in range(len(line)) # if y > -line_height and y < img_h y = y + line_height # And, last but not least, draw the image underneath everything. if image: painter.drawImage(out.rect(), image, image.rect()) painter.end() return out
def print_text(image, text, scene_mode = common.SCENE_MODES.normal, format = TextFormat(), mangle = True): img_w = IMG_W img_h = IMG_H if image: img_w = image.width() img_h = image.height() out = QImage(img_w, img_h, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) # This is a better representation of how the game handles text. painter.setCompositionMode(QPainter.CompositionMode_DestinationOver) painter.setRenderHint(QPainter.Antialiasing, True) lines, lengths, clt_changes = process_text(text, scene_mode, format, mangle) base_x = format.x base_y = format.y line_height = format.h x, y = base_x, base_y cur_clt = 0 text_height = len(lines) * line_height while text_height + y > img_h: y -= line_height center_x = format.x + (format.w / 2.0) right_x = format.x + format.w for i, line in enumerate(lines): # Only bother if we actually see the line. if y > -line_height and y < img_h: line_length = sum(lengths[i]) if format.orient == TEXT_ORIENT.hor: if format.align == TEXT_ALIGN.left: x = base_x elif format.align == TEXT_ALIGN.right: x = right_x - line_length elif format.align == TEXT_ALIGN.center: x = center_x - (line_length / 2.0) elif format.align == TEXT_ALIGN.offcenter: x = center_x - (line_length / 2.0) - 7 for j in range(len(line)): char = line[j] if j in clt_changes[i]: cur_clt = clt_changes[i][j] letter, (xshift, yshift, final_w, final_h) = get_letter(cur_clt, char) final_x = (x + xshift) final_y = (y + yshift) + max(0, (line_height - final_h)) + CLT_STYLES[cur_clt].y_shift painter.drawImage(QRect(final_x, final_y, final_w, final_h), letter, letter.rect()) if format.orient == TEXT_ORIENT.hor: x += lengths[i][j] elif format.orient == TEXT_ORIENT.ver: y += lengths[i][j] if format.orient == TEXT_ORIENT.hor: y += line_height elif format.orient == TEXT_ORIENT.ver: y = base_y x -= line_height # And, last but not least, draw the image underneath everything. if image: painter.drawImage(out.rect(), image, image.rect()) painter.end() return out
def loadImages(self): self.game.board.image = QImage(self.game.board.image) names = self.game.board.territoryNames() progress = QProgressDialog("Loading Board", "", 0, len(names)) progress.setCancelButton(None) progress.setMinimumDuration(0) for (i, name) in enumerate(names): progress.setValue(i) t = self.game.board.getTerritory(name) t.image = QImage(t.image) #generate region map regionOverlay = QImage(self.imageSize(), QImage.Format_ARGB32_Premultiplied) regionOverlay.fill(0) painter = QPainter() painter.begin(regionOverlay) labels = [] for r in self.game.board.regions: regionMask = QImage(self.imageSize(), QImage.Format_ARGB32_Premultiplied) regionMask.fill(0) p = QPainter() p.begin(regionMask) center = QPoint(0, 0) for t in r.territories: p.drawImage(0, 0, t.image) center += QPoint(*t.center) center /= len(r.territories) p.end() regionImage = QImage(self.imageSize(), QImage.Format_ARGB32_Premultiplied) regionImage.fill(0) p.begin(regionImage) p.setCompositionMode(QPainter.CompositionMode_Source) color = [randint(0, 255) for i in range(3)] + [200] p.fillRect(regionImage.rect(), QColor(*color)) p.setCompositionMode(QPainter.CompositionMode_DestinationIn) p.drawImage(0, 0, regionMask) p.end() painter.drawImage(0, 0, regionImage) text = "%s: %d" % (r.name, r.bonus) labels.append((center, text)) for l in labels: (center, text) = l height = painter.fontMetrics().height() + 8 width = painter.fontMetrics().width(text) + 8 painter.setPen(Qt.white) painter.setBrush(QColor(0, 0, 0, 200)) textRect = QRect(0, 0, width, height) textRect.moveCenter(center) painter.drawRect(textRect) painter.drawText(textRect, Qt.AlignCenter, text) painter.end() regionMap = self.game.board.image.copy() painter.begin(regionMap) painter.drawImage(0, 0, regionOverlay) painter.end() self.regionMap = QPixmap.fromImage(regionMap) self.scaledRegionMap = self.regionMap self.ownershipMap = QPixmap.fromImage(self.game.board.image) self.scaledOwnershipMap = self.ownershipMap troopCountMap = QImage(self.game.board.image.size(), QImage.Format_ARGB32_Premultiplied) troopCountMap.fill(0) self.troopCountMap = QPixmap.fromImage(troopCountMap) self.scaledTroopCountMap = self.troopCountMap
def print_text(image, text, scene_mode=common.SCENE_MODES.normal, format=TextFormat(), mangle=True): img_w = IMG_W img_h = IMG_H if image: img_w = image.width() img_h = image.height() out = QImage(img_w, img_h, QImage.Format_ARGB32_Premultiplied) out.fill(QColor(0, 0, 0, 0).rgba()) painter = QPainter(out) # This is a better representation of how the game handles text. painter.setCompositionMode(QPainter.CompositionMode_DestinationOver) painter.setRenderHint(QPainter.Antialiasing, True) lines, lengths, clt_changes = process_text(text, scene_mode, format, mangle) base_x = format.x base_y = format.y line_height = format.h x, y = base_x, base_y cur_clt = 0 text_height = len(lines) * line_height while text_height + y > img_h: y -= line_height center_x = format.x + (format.w / 2.0) right_x = format.x + format.w for i, line in enumerate(lines): # Only bother if we actually see the line. if y > -line_height and y < img_h: line_length = sum(lengths[i]) if format.orient == TEXT_ORIENT.hor: if format.align == TEXT_ALIGN.left: x = base_x elif format.align == TEXT_ALIGN.right: x = right_x - line_length elif format.align == TEXT_ALIGN.center: x = center_x - (line_length / 2.0) elif format.align == TEXT_ALIGN.offcenter: x = center_x - (line_length / 2.0) - 7 for j in range(len(line)): char = line[j] if j in clt_changes[i]: cur_clt = clt_changes[i][j] letter, (xshift, yshift, final_w, final_h) = get_letter(cur_clt, char) final_x = (x + xshift) final_y = (y + yshift) + max( 0, (line_height - final_h)) + CLT_STYLES[cur_clt].y_shift painter.drawImage(QRect(final_x, final_y, final_w, final_h), letter, letter.rect()) if format.orient == TEXT_ORIENT.hor: x += lengths[i][j] elif format.orient == TEXT_ORIENT.ver: y += lengths[i][j] if format.orient == TEXT_ORIENT.hor: y += line_height elif format.orient == TEXT_ORIENT.ver: y = base_y x -= line_height # And, last but not least, draw the image underneath everything. if image: painter.drawImage(out.rect(), image, image.rect()) painter.end() return out