Example #1
1
    def createPixmap(self):
        """Creates the pixmap shown when this label is dragged."""
        font_metric = QFontMetrics(QFont())
        text_size = font_metric.size(Qt.TextSingleLine, self.text)
        image = QImage(text_size.width() + 4, text_size.height() + 4,
            QImage.Format_ARGB32_Premultiplied)
        image.fill(qRgba(240, 240, 120, 255))

        painter = QPainter()
        painter.begin(image)
        painter.setFont(QFont())
        painter.setBrush(Qt.black)
        painter.drawText(QRect(QPoint(2, 2), text_size), Qt.AlignCenter,
            self.text)
        painter.end()
        return image
    def save_image_to(self, path):

        TOP_MARGIN = 50
        LEFT_MARGIN = 50

        # Determine the size of the entire graph
        graph_size = self._graph_size()

        image_size = QSize(graph_size.width() + LEFT_MARGIN * 2,
                           graph_size.height() + TOP_MARGIN * 2
                           )

        image = QImage(image_size, QImage.Format_ARGB32)
        image.fill(Qt.white)  # white background

        painter = QPainter(image)
        painter.translate(TOP_MARGIN, LEFT_MARGIN)
        painter.setRenderHint(QPainter.TextAntialiasing)
        self._paint(painter,
                    QPoint(-TOP_MARGIN, -LEFT_MARGIN),
                    QPoint(image_size.width(), image_size.height())
                    )
        painter.end()

        image.save(path)
Example #3
0
    def saveBMC(self):
        """
        .. TODO:: Save a Brother PEL image (An 8bpp, 130x113 pixel monochromatic? bitmap image) Why 8bpp when only 1bpp is needed?

        .. TODO:: Should BMC be limited to ~32KB or is this a mix up with Bitmap Cache?
        .. TODO:: Is there/should there be other embedded data in the bitmap besides the image itself?
        .. NOTE:: Can save a Singer BMC image (An 8bpp, 130x113 pixel colored bitmap image)
        """
        # TODO: figure out how to center the image, right now it just plops it to the left side.
        img = QImage(150, 150, QImage.Format_ARGB32_Premultiplied)
        img.fill(qRgb(255, 255, 255))
        extents = self.gscene.itemsBoundingRect()  # QRectF

        painter = QPainter(img)
        targetRect = QRectF(0, 0, 150, 150)
        if self.mainWin.getSettingsPrintingDisableBG():  # TODO: Make BMC background into it's own setting?
            brush = self.gscene.backgroundBrush()  # QBrush
            self.gscene.setBackgroundBrush(Qt.NoBrush)
            self.gscene.update()
            self.gscene.render(painter, targetRect, extents, Qt.KeepAspectRatio)
            self.gscene.setBackgroundBrush(brush)

        else:
            self.gscene.update()
            self.gscene.render(painter, targetRect, extents, Qt.KeepAspectRatio)

        img.convertToFormat(QImage.Format_Indexed8, Qt.ThresholdDither | Qt.AvoidDither).save("test.bmc", "BMP")
Example #4
0
    def render(self, fileName, width, height):
        self.setViewportSize(QSize(width, height))

        fileInfo = QFileInfo(fileName)
        dir = QDir()
        dir.mkpath(fileInfo.absolutePath())
        viewportSize = self.viewportSize()
        pageSize = self.mainFrame().contentsSize()
        if pageSize.isEmpty():
            return False

        buffer = QImage(pageSize, QImage.Format_ARGB32)
        buffer.fill(qRgba(255, 255, 255, 0))
        p =  QPainter(buffer)

        p.setRenderHint( QPainter.Antialiasing,          True)
        p.setRenderHint( QPainter.TextAntialiasing,      True)
        p.setRenderHint( QPainter.SmoothPixmapTransform, True)

        self.setViewportSize(pageSize)
        self.mainFrame().render(p)
        p.end()

        self.setViewportSize(viewportSize)

        return buffer.save(fileName)
Example #5
0
    def drawIconWithShadow(icon, rect, p, iconMode, radius, color, offset):
        cache = QPixmap()
        pixmapName = "icon {0} {1} {2}".format(icon.cacheKey(), iconMode, rect.height())

        if not QPixmapCache.find(pixmapName, cache):
            px = icon.pixmap(rect.size())
            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(im.height()):
                    scanLine = im.scanLine(y)
                    for x in range(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(QPoint(radius, radius), px)
            tmpPainter.end()

            # blur the alpha channel
            blurred = QImage(tmp.size(), QImage.Format_ARGB32_Premultiplied)
            blurred.fill(Qt.transparent)
            blurPainter = QPainter(blurred)
            # todo : blur image
            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(QPoint(radius, radius) + offset, px)
            QPixmapCache.insert(pixmapName, cache)

        targetRect = cache.rect()
        targetRect.moveCenter(rect.center())
        p.drawPixmap(targetRect.topLeft() - offset, cache)
Example #6
0
    def set_clipboard_image(self):
        """Export the formatted output to an image and store it in the
        clipboard.

        The image stored in the clipboard is a PNG file with alpha
        transparency.

        """
        div = self.view.page().mainFrame().findFirstElement('.output')
        images = {}
        for background in (Qt.transparent, Qt.white):
            image = QImage(div.geometry().size(),
                           QImage.Format_ARGB32_Premultiplied)
            image.fill(background)
            painter = QPainter(image)
            div.render(painter)
            painter.end()
            images[background] = image

        # Windows needs this buffer hack to get alpha transparency in
        # the copied PNG.
        buffer_ = QBuffer()
        buffer_.open(QIODevice.WriteOnly)
        images[Qt.transparent].save(buffer_, 'PNG')
        buffer_.close()
        data = QMimeData()
        data.setData('PNG', buffer_.data())
        data.setImageData(images[Qt.white])
        QApplication.clipboard().setMimeData(data)
    def resizeImage(self, image, newSize):
        if image.size() == newSize:
            return
        newImage = QImage(newSize, QImage.Format_RGB32)
        newImage.fill(qRgb(255, 255, 255))
        painter = QPainter(newImage)
        painter.drawImage(QtCore.QPoint(0, 0), image)

        self.image = newImage
Example #8
0
 def __init__(self, svgImage, width, height, parent=None):
     super(SvgButton, self).__init__(parent)
     svg_renderer = QSvgRenderer(svgImage)
     image = QImage(width, height, QImage.Format_ARGB32)
     # Set the ARGB to 0 to prevent rendering artifacts
     image.fill(0x00000000)
     svg_renderer.render(QPainter(image))
     pixmap = QPixmap.fromImage(image)
     icon = QIcon(pixmap)
     self.setIcon(icon)
     self.setIconSize(QSize(width, height))
Example #9
0
 def __init__(self, svgImage, width, height, parent=None):
     super(SvgButton, self).__init__(parent)
     svg_renderer = QSvgRenderer(svgImage)
     image = QImage(width, height, QImage.Format_ARGB32)
     # Set the ARGB to 0 to prevent rendering artifacts
     image.fill(0x00000000)
     svg_renderer.render(QPainter(image))
     pixmap = QPixmap.fromImage(image)
     icon = QIcon(pixmap)
     self.setIcon(icon)
     self.setIconSize(QSize(width, height))
Example #10
0
    def createPixmap(self):
        """Creates the pixmap shown when this label is dragged."""
        font_metric = QFontMetrics(QFont())
        text_size = font_metric.size(Qt.TextSingleLine, self.text)
        image = QImage(text_size.width() + 4,
                       text_size.height() + 4,
                       QImage.Format_ARGB32_Premultiplied)
        image.fill(qRgba(240, 240, 120, 255))

        painter = QPainter()
        painter.begin(image)
        painter.setFont(QFont())
        painter.setBrush(Qt.black)
        painter.drawText(QRect(QPoint(2, 2), text_size), Qt.AlignCenter,
                         self.text)
        painter.end()
        return image
Example #11
0
    def save_invoice(self, ok):
        self.enable_ui()
        if ok:
            frame = self.webpage.mainFrame()
            image = QImage(frame.contentsSize(), QImage.Format_ARGB32_Premultiplied)
            image.fill(Qt.transparent);

            painter = QPainter(image)
            painter.setRenderHint(QPainter.Antialiasing, True);
            painter.setRenderHint(QPainter.TextAntialiasing, True);
            painter.setRenderHint(QPainter.SmoothPixmapTransform, True);
            frame.documentElement().render(painter);
            painter.end();

            image.save(self.invoice_filename)
            self.load_invoice()
        else:
            title = "An error occured"
            message = "Could not load invoice." \
                    + "\nPlease check your internet connection."

            QMessageBox.critical(self, title, message)
 def setSettings(self):
     """Set color, verbosity and logging options."""
     self.logDock.setBgColor(self.config.get('Appearance', 'log_bg_color'))
     image = QImage(10, 10, QImage.Format_RGB32)
     image.fill(QColor(self.config.get('Appearance', 'circ_bg_color')))
     image.setPixel(0, 0, QColor(0, 0, 0).rgb())
     self.view.scene().setBackgroundBrush(QBrush(QPixmap.fromImage(image)))
     Plug.setInputVerbose = self.config.getboolean(
         'LogVerbosity', 'input_chang')
     Plug.setOutputVerbose = self.config.getboolean(
         'LogVerbosity', 'output_chang')
     Plug.connectVerbose = self.config.getboolean(
         'LogVerbosity', 'conn_discon_io')
     Plug.addPlugVerbose = self.config.getboolean(
         'LogVerbosity', 'adding_io')
     Circuit.addCircuitVerbose = self.config.getboolean(
         'LogVerbosity', 'adding_circ')
     Circuit.removePlugVerbose = self.config.getboolean(
         'LogVerbosity', 'removing_io')
     Circuit.removeCircuitVerbose = self.config.getboolean(
         'LogVerbosity', 'removing_circ')
     Circuit.detailedRemoveVerbose = self.config.getboolean(
         'LogVerbosity', 'detailed_rm')
     ClockThread.spd = self.config.getfloat(
         'Clock', 'speed')
     if self.config.getboolean('LogHandlers', 'gui'):
         log.addHandler(self.logDock.handler)
     else:
         log.removeHandler(self.logDock.handler)
     if self.config.getboolean('LogHandlers', 'stdout'):
         log.addHandler(stdoutHandler)
     else:
         log.removeHandler(stdoutHandler)
     if self.config.getboolean('LogHandlers', 'file'):
         log.addHandler(fileHandler)
     else:
         log.removeHandler(fileHandler)
Example #13
0
class ImagenQImage(BaseImagen):
    def __init__(self):
        super(ImagenQImage, self).__init__()
        self.mode = "No implementado"

    @property
    def size(self):
        return (self.img.width(), self.img.height())

    def fromfile(self, filename):
        self.img = QImage(filename)

    def from_instance(self, qimage):
        self.img = qimage

    def empty(self, size, mode=QImage.Format_RGB888):
        self.img = QImage(size[0], size[1], mode)
        self.img.fill(qRgb(0, 0, 0))  #Rellenamos la imagen con negro

    def getpixel(self, xy):
        color = self.img.pixel(xy[0], xy[1])
        return (qRed(color), qGreen(color), qBlue(color))

    def putpixel(self, xy, value):
        self.img.setPixel(xy[0], xy[1], qRgb(value[0], value[1], value[2]))

    def get_img(self):
        return self.img

    def save(self, filename):
        self.img.save(filename, format="BMP", quality=100)

    def from_opencv(self, img_opencv):
        dst = cv2.cvtColor(img_opencv, cv2.COLOR_BGR2RGB)
        qim = QImage(dst.data, dst.shape[1], dst.shape[0], dst.strides[0],
                     QImage.Format_RGB888)
        self.img = qim.copy()
Example #14
0
File: imagen.py Project: zikofv/pdi
class ImagenQImage(BaseImagen):
  def __init__(self):
    super(ImagenQImage, self).__init__()
    self.mode = "No implementado"

  @property
  def size(self):
    return (self.img.width(), self.img.height())

  def fromfile(self, filename):
    self.img = QImage(filename)

  def from_instance(self, qimage):
    self.img = qimage

  def empty(self, size, mode=QImage.Format_RGB888):
    self.img = QImage(size[0], size[1], mode)
    self.img.fill(qRgb(0,0,0))#Rellenamos la imagen con negro

  def getpixel(self, xy):
    color = self.img.pixel(xy[0], xy[1])
    return (qRed(color), qGreen(color), qBlue(color))

  def putpixel(self, xy, value):
    self.img.setPixel(xy[0], xy[1], qRgb(value[0], value[1], value[2]))

  def get_img(self):
    return self.img

  def save(self, filename):
    self.img.save(filename, format="BMP", quality=100)

  def from_opencv(self, img_opencv):
    dst = cv2.cvtColor(img_opencv, cv2.COLOR_BGR2RGB)
    qim = QImage(dst.data, dst.shape[1], dst.shape[0], dst.strides[0], QImage.Format_RGB888)
    self.img = qim.copy()
Example #15
0
class Render():
    '''Transform the numpy data into a renderable image suitable for screen'''
    def __init__(self, world):
        self.world = world
        for k in self.world:
            exec('self.' + k + ' = self.world[k]')

        self.width, self.height = self.elevation.shape
        self.image = QImage(self.width, self.height, QImage.Format_RGB32)
        self.image.fill(QtGui.QColor(0, 0, 0))

    def hex2rgb(self, hexcolor):
        r = (hexcolor >> 16) & 0xFF
        g = (hexcolor >> 8) & 0xFF
        b = hexcolor & 0xFF
        return [r, g, b]

    def rgb2hex(self, rgb):
        assert (len(rgb) == 3)
        return '#%02x%02x%02x' % rgb

    def convert(self, mapType, seaLevel=None):
        if seaLevel:
            seaLevel /= 100.0  # reduce to 0.0 to 1.0 range

        background = []
        if mapType == "heightmap":
            heightmap = self.elevation * 255  # convert to greyscale
            for x in range(self.width):
                for y in range(self.height):
                    gValue = heightmap[x, y]
                    self.image.setPixel(
                        x, y,
                        QtGui.QColor(gValue, gValue, gValue).rgb())

        elif mapType == "sealevel":
            for x in range(self.width):
                for y in range(self.height):
                    elevation = self.elevation[x, y]
                    gValue = elevation * 255
                    if elevation <= seaLevel:
                        self.image.setPixel(x, y,
                                            QtGui.QColor(0, 0, gValue).rgb())
                    else:
                        self.image.setPixel(
                            x, y,
                            QtGui.QColor(gValue, gValue, gValue).rgb())

        elif mapType == "elevation":
            for x in range(self.width):
                for y in range(self.height):
                    elevation = self.elevation[x, y]
                    if elevation <= seaLevel:
                        if elevation < seaLevel / 4.0:
                            self.image.setPixel(x, y, COLOR_DEEPSEA)
                        elif elevation < seaLevel / 2.0:
                            self.image.setPixel(x, y, COLOR_SEA)
                        else:
                            self.image.setPixel(x, y, COLOR_BLUE)
                    else:
                        if elevation < 0.65:
                            self.image.setPixel(x, y, COLOR_GRASSLAND)
                        elif elevation < 0.95:
                            self.image.setPixel(x, y, COLOR_HILLS)
                        else:
                            self.image.setPixel(x, y, COLOR_WHITE)

        elif mapType == "heatmap":
            for x in range(self.width):
                for y in range(self.height):
                    gValue = self.temperature[x, y]
                    self.image.setPixel(
                        x, y,
                        QtGui.QColor(gValue * 255, gValue * 128,
                                     (1 - gValue) * 255).rgb())

        elif mapType == "rawheatmap":
            temperature = self.temperature * 255  # convert to greyscale
            for x in range(self.width):
                for y in range(self.height):
                    gValue = temperature[x, y]
                    self.image.setPixel(
                        x, y,
                        QtGui.QColor(gValue, gValue, gValue).rgb())

        elif mapType == 'windmap':
            for x in range(self.width):
                for y in range(self.height):
                    gValue = self.wind[x, y]
                    self.image.setPixel(x, y,
                                        QtGui.QColor(0, gValue * 255, 0).rgb())

        elif mapType == 'rainmap':
            for x in range(self.width):
                for y in range(self.height):
                    gValue = self.rainfall[x, y]
                    self.image.setPixel(
                        x, y,
                        QtGui.QColor(gValue * 100, gValue * 100,
                                     gValue * 255).rgb())

        elif mapType == 'windandrainmap':
            for x in range(self.width):
                for y in range(self.height):
                    rain = int(255 * min(self.wind[x, y], 1.0))
                    wind = int(255 * min(self.rainfall[x, y], 1.0))
                    self.image.setPixel(x, y,
                                        QtGui.QColor(0, wind, rain).rgb())

        elif mapType == 'drainagemap':
            drainage = self.drainage * 255  # convert to greyscale
            for x in range(self.width):
                for y in range(self.height):
                    gValue = drainage[x, y]
                    self.image.setPixel(
                        x, y,
                        QtGui.QColor(gValue, gValue, gValue).rgb())

        elif mapType == 'rivermap':
            for x in range(self.width):
                for y in range(self.height):
                    gValue = self.elevation[x, y] * 255
                    if self.elevation[x, y] <= seaLevel:
                        self.image.setPixel(x, y,
                                            QtGui.QColor(0, 0, gValue).rgb())
                    else:
                        rgb = QtGui.QColor(gValue, gValue, gValue).rgb()
                        if self.rivers[x, y] > 0.0:
                            rgb = COLOR_COBALT
                        if self.lakes[x, y] > 0.0:
                            rgb = COLOR_AZURE
                        self.image.setPixel(x, y, rgb)

        elif mapType == 'biomemap':
            for x in range(self.width):
                for y in range(self.height):
                    self.image.setPixel(x, y, self.biomeColour[x, y])

        elif mapType == "erosionmap":
            erosion = self.erosion * 255  # convert to greyscale
            for x in range(self.width):
                for y in range(self.height):
                    gValue = erosion[x, y]
                    self.image.setPixel(
                        x, y,
                        QtGui.QColor(gValue, gValue, gValue).rgb())

        elif mapType == "erosionappliedmap":
            erosion = (self.elevation -
                       self.erosion) * 255  # convert to greyscale
            for x in range(self.width):
                for y in range(self.height):
                    gValue = erosion[x, y]
                    self.image.setPixel(
                        x, y,
                        QtGui.QColor(gValue, gValue, gValue).rgb())

        else:  # something bad happened...
            print(
                "did not get a valid map type, check your bindings programmer man!"
            )
            print(len(background), background, mapType)
            from numpy import zeros
            background = zeros((self.width, self.height), dtype="int32")

        return self.image
class PaintArea(QWidget):
    tools = {
        'pen': True,
        'line': False,
        'rect': False,
        'roundRect': False,
        'circle': False,
        'eraser': False,
    }

    def __init__(self, parent=None):
        super(PaintArea, self).__init__(parent)
        self.autoFillBackground = True
        self.myPenWidth = 3
        self.myPenColor = QColor(100, 100, 100, 255)
        self.size_w = 500
        self.size_h = 500
        imageSize = QtCore.QSize(self.size_w, self.size_h)
        self.image = QImage(imageSize, QImage.Format_RGB32)
        self.imagePreview = QImage(imageSize, QImage.Format_ARGB32)
        self.lastPoint = QtCore.QPoint()
        self.setMinimumSize(imageSize)
        self.setMaximumSize(imageSize)

    def saveImage(self, fileName, fileFormat='png'):
        visibleImage = self.image
        self.resizeImage(visibleImage, self.size())
        if visibleImage.save(fileName, fileFormat):
            self.modified = False
            return True
        else:
            return False

    def setPenColor(self, newColor):
        self.myPenColor = newColor

    def setPenWidth(self, newWidth):
        self.myPenWidth = newWidth

    def clearImage(self):
        self.image.fill(qRgb(255, 255, 255))
        self.modified = True
        self.update()

    def clearImagePreview(self):
        self.imagePreview.fill(QtCore.Qt.transparent)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.firstPoint_x = event.x()
            self.firstPoint_y = event.y()
            self.scribbling = True

    def mouseMoveEvent(self, event):
        if (event.buttons() & QtCore.Qt.LeftButton) and self.scribbling:
            if self.tools['pen'] or self.tools['eraser']:
                self.draw(event.x(), event.y())
            else:
                self.flag = False
                self.drawPreview(event.x(), event.y())

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton and self.scribbling:
            self.flag = True
            self.draw(event.x(), event.y())
            self.scribbling = False

    def setTool(self, st):
        for i in self.tools:
            self.tools[i] = False
        self.tools[st] = True

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawImage(event.rect(), self.image)
        painter.drawImage(event.rect(), self.imagePreview)
        self.clearImagePreview()

    def draw(self, endPoint_x, endPoint_y):
        painter = QPainter(self.image)

        painter.setPen(QPen(
            self.myPenColor, self.myPenWidth, QtCore.Qt.SolidLine,
            QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
        painter.setClipping(True)

        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
        painter.setRenderHint(QPainter.HighQualityAntialiasing, True)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setCompositionMode(QPainter.CompositionMode())

        if self.tools['circle']:
            x1 = self.firstPoint_x
            y1 = self.firstPoint_y
            x2 = endPoint_x
            y2 = endPoint_y
            painter.drawEllipse(x1, y1, (x2 - x1), (y2 - y1))

        if self.tools['eraser']:
            painter.setPen(QPen(QtCore.Qt.white, 10, QtCore.Qt.SolidLine))
            painter.drawLine(
                self.firstPoint_x, self.firstPoint_y, endPoint_x, endPoint_y)
            self.firstPoint_x = endPoint_x
            self.firstPoint_y = endPoint_y

        if self.tools['pen']:
            painter.drawLine(
                self.firstPoint_x, self.firstPoint_y, endPoint_x, endPoint_y)
            self.firstPoint_x = endPoint_x
            self.firstPoint_y = endPoint_y

        if self.tools['line'] and self.flag:
            painter.drawLine(
                self.firstPoint_x, self.firstPoint_y, endPoint_x, endPoint_y)

        if self.tools['rect']:
            dx = endPoint_x - self.firstPoint_x
            dy = endPoint_y - self.firstPoint_y
            painter.drawRect(self.firstPoint_x, self.firstPoint_y, dx, dy)

        if self.tools['roundRect']:
            x1 = self.firstPoint_x
            y1 = self.firstPoint_y
            dx = endPoint_x - self.firstPoint_x
            dy = endPoint_y - self.firstPoint_y
            if x1 > endPoint_x and y1 > endPoint_y:
                painter.drawRoundedRect(
                    endPoint_x, endPoint_y, -dx, -dy, 20, 20, 0)
            else:
                painter.drawRoundedRect(x1, y1, dx, dy, 20., 20.)

        self.modified = True
        self.update()

    def drawPreview(self, endPoint_x, endPoint_y):
        painter = QPainter(self.imagePreview)
        painter.setPen(QPen(
            self.myPenColor,
            self.myPenWidth,
            QtCore.Qt.SolidLine,
            QtCore.Qt.RoundCap,
            QtCore.Qt.RoundJoin))
        painter.setClipping(True)

        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
        painter.setRenderHint(QPainter.HighQualityAntialiasing, True)
        painter.setRenderHint(QPainter.Antialiasing, True)

        painter.setOpacity(0.5)

        if self.tools['circle']:
            x1 = self.firstPoint_x
            y1 = self.firstPoint_y
            x2 = endPoint_x
            y2 = endPoint_y
            painter.drawEllipse(x1, y1, (x2 - x1), (y2 - y1))

        if self.tools['line']:
            painter.drawLine(
                self.firstPoint_x, self.firstPoint_y, endPoint_x, endPoint_y)

        if self.tools['rect']:
            painter.drawRect(
                self.firstPoint_x, self.firstPoint_y,
                endPoint_x - self.firstPoint_x,
                endPoint_y - self.firstPoint_y)

        if self.tools['roundRect']:
            x1 = self.firstPoint_x
            y1 = self.firstPoint_y
            dx = endPoint_x - self.firstPoint_x
            dy = endPoint_y - self.firstPoint_y
            if x1 > endPoint_x and y1 > endPoint_y:
                painter.drawRoundedRect(
                    endPoint_x, endPoint_y, -dx, -dy, 20, 20, 0)
            else:
                painter.drawRoundedRect(x1, y1, dx, dy, 20., 20.)

        self.update()

    def rotate(self):
        myTransform = QTransform()
        myTransform.rotate(90)
        self.image = self.image.transformed(myTransform)
        self.update()

    def mirror_h(self):
        self.image = self.image.mirrored(False, True)
        self.update()

    def mirror_w(self):
        self.image = self.image.mirrored(True, False)
        self.update()

    def resizeImage(self, image, newSize):
        if image.size() == newSize:
            return
        newImage = QImage(newSize, QImage.Format_RGB32)
        newImage.fill(qRgb(255, 255, 255))
        painter = QPainter(newImage)
        painter.drawImage(QtCore.QPoint(0, 0), image)

        self.image = newImage

    def isModified(self):
        return self.modified

    def penColor(self):
        return self.myPenColor

    def penWidth(self):
        return self.myPenWidth
Example #17
0
class Render():
    '''Transform the numpy data into a renderable image suitable for screen'''

    def __init__( self, world ):
        self.world = world
        for k in self.world:
            exec( 'self.' + k + ' = self.world[k]' )

        self.width, self.height = self.elevation.shape
        self.image = QImage( self.width, self.height, QImage.Format_RGB32 )
        self.image.fill(QtGui.QColor(0,0,0))

    def hex2rgb( self, hexcolor ):
        r = ( hexcolor >> 16 ) & 0xFF;
        g = ( hexcolor >> 8 ) & 0xFF;
        b = hexcolor & 0xFF;
        return [r, g, b]

    def rgb2hex( self, rgb ):
        assert( len( rgb ) == 3 )
        return '#%02x%02x%02x' % rgb

    def convert( self, mapType, seaLevel = None ):
        if seaLevel:
            seaLevel /= 100.0 # reduce to 0.0 to 1.0 range
            
        background = []
        if mapType == "heightmap":
            heightmap = self.elevation * 255 # convert to greyscale
            for x in range( self.width ):
                for y in range( self.height ):
                    gValue = heightmap[x, y]
                    self.image.setPixel( x, y, QtGui.QColor( gValue, gValue, gValue ).rgb() )

        elif mapType == "sealevel":
            for x in range( self.width ):
                for y in range( self.height ):
                    elevation = self.elevation[x, y]
                    gValue = elevation * 255
                    if elevation <= seaLevel:
                        self.image.setPixel( x, y, QtGui.QColor( 0, 0, gValue ).rgb() )
                    else:
                        self.image.setPixel( x, y, QtGui.QColor( gValue, gValue, gValue ).rgb() )

        elif mapType == "elevation":
            for x in range( self.width ):
                for y in range( self.height ):
                    elevation = self.elevation[x, y]
                    if elevation <= seaLevel:
                        if elevation < seaLevel/4.0:
                            self.image.setPixel( x, y, COLOR_DEEPSEA )
                        elif elevation < seaLevel/2.0:
                            self.image.setPixel( x, y, COLOR_SEA )
                        else:
                            self.image.setPixel( x, y, COLOR_BLUE )
                    else:
                        if elevation < 0.65:
                            self.image.setPixel( x, y, COLOR_GRASSLAND )
                        elif elevation < 0.95:
                            self.image.setPixel( x, y, COLOR_HILLS )
                        else:
                            self.image.setPixel( x, y, COLOR_WHITE )

        elif mapType == "heatmap":
            for x in range( self.width ):
                for y in range( self.height ):
                    gValue = self.temperature[x, y]
                    self.image.setPixel( x, y, QtGui.QColor( gValue * 255, gValue * 128, ( 1 - gValue ) * 255 ).rgb() )

        elif mapType == "rawheatmap":
            temperature = self.temperature * 255 # convert to greyscale
            for x in range( self.width ):
                for y in range( self.height ):
                    gValue = temperature[x, y]
                    self.image.setPixel( x, y, QtGui.QColor( gValue, gValue, gValue ).rgb() )

        elif mapType == 'windmap':
            for x in range( self.width ):
                for y in range( self.height ):
                    gValue = self.wind[x, y]
                    self.image.setPixel( x, y, QtGui.QColor( 0, gValue * 255, 0 ).rgb() )

        elif mapType == 'rainmap':
            for x in range( self.width ):
                for y in range( self.height ):
                    gValue = self.rainfall[x, y]
                    self.image.setPixel( x, y, QtGui.QColor( gValue * 100, gValue * 100, gValue * 255 ).rgb() )

        elif mapType == 'windandrainmap':
            for x in range( self.width ):
                for y in range( self.height ):
                    rain = int( 255 * min( self.wind[x, y], 1.0 ) )
                    wind = int( 255 * min( self.rainfall[x, y], 1.0 ) )
                    self.image.setPixel( x, y, QtGui.QColor( 0, wind, rain ).rgb() )

        elif mapType == 'drainagemap':
            drainage = self.drainage * 255 # convert to greyscale
            for x in range( self.width ):
                for y in range( self.height ):
                    gValue = drainage[x, y]
                    self.image.setPixel( x, y, QtGui.QColor( gValue, gValue, gValue ).rgb() )

        elif mapType == 'rivermap':
            for x in range( self.width ):
                for y in range( self.height ):
                    gValue = self.elevation[x, y] * 255
                    if self.elevation[x, y] <= seaLevel: 
                        self.image.setPixel( x, y, QtGui.QColor( 0, 0, gValue ).rgb() )
                    else:
                        rgb = QtGui.QColor( gValue, gValue, gValue ).rgb()
                        if self.rivers[x, y] > 0.0:
                            rgb = COLOR_COBALT
                        if self.lakes[x, y] > 0.0:
                            rgb = COLOR_AZURE
                        self.image.setPixel( x, y, rgb )

        elif mapType == 'biomemap':
            for x in range( self.width ):
                for y in range( self.height ):
                    self.image.setPixel( x, y, self.biomeColour[x, y] )

        elif mapType == "erosionmap":
            erosion = self.erosion * 255 # convert to greyscale
            for x in range( self.width ):
                for y in range( self.height ):
                    gValue = erosion[x, y] 
                    self.image.setPixel( x, y, QtGui.QColor( gValue, gValue, gValue ).rgb() )

        elif mapType == "erosionappliedmap":
            erosion = ( self.elevation - self.erosion ) *  255 # convert to greyscale
            for x in range( self.width ):
                for y in range( self.height ):
                    gValue = erosion[x, y]
                    self.image.setPixel( x, y, QtGui.QColor( gValue, gValue, gValue ).rgb() )

        else: # something bad happened...
            print("did not get a valid map type, check your bindings programmer man!")
            print(len( background ), background, mapType)
            from numpy import zeros
            background = zeros( ( self.width, self.height ), dtype = "int32" )

        return self.image
Example #18
0
    def drawArrow(element, painter, option):
        # From windows style but modified to enable AA
        if option.rect.width() <= 1 or option.rect.height() <= 1:
            return

        r = option.rect
        size = min(r.height(), r.width())
        pixmap = QPixmap()
        pixmapName = "arrow-{0}-{1}-{2}-{3}-{4}".format(
            "$qt_ia", int(option.state), element, size, option.palette.cacheKey()
        )
        if not QPixmapCache.find(pixmapName, pixmap):
            border = size / 5
            sqsize = 2 * (size / 2)
            image = QImage(sqsize, sqsize, QImage.Format_ARGB32)
            image.fill(Qt.transparent)
            imagePainter = QPainter(image)
            imagePainter.setRenderHint(QPainter.Antialiasing, True)
            imagePainter.translate(0.5, 0.5)
            a = QPolygon()
            if element == QStyle.PE_IndicatorArrowUp:
                a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize - border, sqsize / 2)
            elif element == QStyle.PE_IndicatorArrowDown:
                a.setPoints(3, border, sqsize / 2, sqsize / 2, sqsize - border, sqsize - border, sqsize / 2)
            elif element == QStyle.PE_IndicatorArrowRight:
                a.setPoints(3, sqsize - border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border)
            elif element == QStyle.PE_IndicatorArrowLeft:
                a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border)
            else:
                pass

        bsx = 0
        bsy = 0

        if option.state & QStyle.State_Sunken:
            bsx = qApp.style().pixelMetric(QStyle.PM_ButtonShiftHorizontal)
            bsy = qApp.style().pixelMetric(QStyle.PM_ButtonShiftVertical)

        bounds = a.boundingRect()
        sx = sqsize / 2 - bounds.center().x() - 1
        sy = sqsize / 2 - bounds.center().y() - 1
        imagePainter.translate(sx + bsx, sy + bsy)

        if not (option.state & QStyle.State_Enabled):
            imagePainter.setBrush(option.palette.mid().color())
            imagePainter.setPen(option.palette.mid().color())
        else:
            shadow = QColor(0, 0, 0, 100)
            imagePainter.translate(0, 1)
            imagePainter.setPen(shadow)
            imagePainter.setBrush(shadow)
            foreGround = QColor(255, 255, 255, 210)
            imagePainter.drawPolygon(a)
            imagePainter.translate(0, -1)
            imagePainter.setPen(foreGround)
            imagePainter.setBrush(foreGround)

        imagePainter.drawPolygon(a)
        imagePainter.end()
        pixmap = QPixmap.fromImage(image)
        QPixmapCache.insert(pixmapName, pixmap)

        xOffset = r.x() + (r.width() - size) / 2
        yOffset = r.y() + (r.height() - size) / 2
        painter.drawPixmap(xOffset, yOffset, pixmap)