Esempio n. 1
0
    def _create_pixmap_from_symbol(self, symbol, scale_factor, padding):
        context = QgsRenderContext()
        context.setScaleFactor(scale_factor)

        pixmap = QgsSymbolLayerUtils.symbolPreviewPixmap(
            symbol, QSize(142, 71), padding, context)
        return pixmap
Esempio n. 2
0
def getLegend(layer, renderer, outputProjectFileName, safeLayerName):
    if isinstance(renderer, QgsSingleSymbolRenderer):
        symbol = renderer.symbol()
        legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(
            symbol, QSize(16, 16))
        legendIcon.save(
            os.path.join(outputProjectFileName, "legend",
                         safeLayerName + ".png"))
        legend = ('<img src="legend/' + safeLayerName + '.png" /> ')
        legend += layer.name()
    else:
        if isinstance(renderer, QgsCategorizedSymbolRenderer):
            classes = renderer.categories()
        elif isinstance(renderer, QgsGraduatedSymbolRenderer):
            classes = renderer.ranges()
        elif isinstance(renderer, QgsRuleBasedRenderer):
            classes = renderer.rootRule().children()
        legend = layer.name().replace("'", "\\'") + "<br />"
        legend += "<table>"
        for cnt, c in enumerate(classes):
            symbol = c.symbol()
            legend = iconLegend(symbol, c, outputProjectFileName,
                                safeLayerName, legend, cnt)
        legend += "</table>"
        symbol = classes[0].symbol()
    return (legend, symbol)
Esempio n. 3
0
def graduated(layer, renderer, legendFolder, sln, stylesFolder, layer_alpha,
              feedback):
    # cluster = False
    ranges = []
    elseif = ""
    useAnyMapUnits = False
    for cnt, ran in enumerate(renderer.ranges()):
        legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(
            ran.symbol(), QSize(16, 16))
        legendIcon.save(
            os.path.join(legendFolder, sln + "_" + str(cnt) + ".png"))
        (symbolstyle, pattern, setPattern,
         useMapUnits) = getSymbolAsStyle(ran.symbol(), stylesFolder,
                                         layer_alpha, renderer, sln, layer,
                                         feedback)
        ranges.append(
            """%sif (value >= %f && value <= %f) {
            style = %s
                    }""" %
            (elseif, ran.lowerValue(), ran.upperValue(), symbolstyle))
        elseif = " else "
        if useMapUnits:
            useAnyMapUnits = True
    style = "".join(ranges)
    value = getValue(layer, renderer)
    return (style, pattern, setPattern, value, useAnyMapUnits)
def getLegend(layer, renderer, outputProjectFileName, safeLayerName):
    if isinstance(renderer, QgsSingleSymbolRenderer):
        symbol = renderer.symbol()
        legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(symbol,
                                                             QSize(16, 16))
        legendIcon.save(os.path.join(outputProjectFileName, "legend",
                                     safeLayerName + ".png"))
        legend = ('<img src="legend/' + safeLayerName + '.png" /> ')
        legend += layer.name()
    else:
        if isinstance(renderer, QgsCategorizedSymbolRenderer):
            classes = renderer.categories()
        elif isinstance(renderer, QgsGraduatedSymbolRenderer):
            classes = renderer.ranges()
        elif isinstance(renderer, QgsRuleBasedRenderer):
            classes = renderer.rootRule().children()
        legend = layer.name().replace("'", "\\'") + "<br />"
        legend += "<table>"
        for cnt, c in enumerate(classes):
            symbol = c.symbol()
            legend = iconLegend(symbol, c, outputProjectFileName,
                                safeLayerName, legend, cnt)
        legend += "</table>"
        symbol = classes[0].symbol()
    return (legend, symbol)
Esempio n. 5
0
def categorized(defs, sln, layer, renderer, legendFolder, stylesFolder,
                layer_alpha):
    cluster = False
    defs += """
function categories_%s(feature, value, size, resolution, labelText,
                       labelFont, labelFill) {
                switch(value.toString()) {""" % sln
    cats = []
    useAnyMapUnits = False
    for cnt, cat in enumerate(renderer.categories()):
        legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(
            cat.symbol(), QSize(16, 16))
        legendIcon.save(
            os.path.join(legendFolder, sln + "_" + unicode(cnt) + ".png"))
        if (cat.value() is not None and cat.value() != ""):
            categoryStr = "case '%s':" % unicode(cat.value()).replace(
                "'", "\\'")
        else:
            categoryStr = "default:"
        (style, pattern, setPattern,
         useMapUnits) = (getSymbolAsStyle(cat.symbol(), stylesFolder,
                                          layer_alpha, renderer, sln, layer))
        if useMapUnits:
            useAnyMapUnits = True
        categoryStr += '''
                    return %s;
                    break;''' % style
        cats.append(categoryStr)
    defs += "\n".join(cats) + "}};"
    style = """
var style = categories_%s(feature, value, size, resolution, labelText,
                          labelFont, labelFill)""" % sln
    value = getValue(layer, renderer)
    return (style, pattern, setPattern, value, defs, useAnyMapUnits)
Esempio n. 6
0
def categorized(defs, sln, layer, renderer, legendFolder, stylesFolder,
                layer_alpha):
    cluster = False
    defs += """
function categories_%s(feature, value, size, resolution, labelText,
                       labelFont, labelFill) {
                switch(value.toString()) {""" % sln
    cats = []
    useAnyMapUnits = False
    for cnt, cat in enumerate(renderer.categories()):
        legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(cat.symbol(),
                                                             QSize(16, 16))
        legendIcon.save(os.path.join(legendFolder,
                                     sln + "_" + unicode(cnt) + ".png"))
        if (cat.value() is not None and cat.value() != ""):
            categoryStr = "case '%s':" % unicode(
                cat.value()).replace("'", "\\'")
        else:
            categoryStr = "default:"
        (style, pattern, setPattern,
         useMapUnits) = (getSymbolAsStyle(cat.symbol(), stylesFolder,
                                          layer_alpha, renderer, sln, layer))
        if useMapUnits:
            useAnyMapUnits = True
        categoryStr += '''
                    return %s;
                    break;''' % style
        cats.append(categoryStr)
    defs += "\n".join(cats) + "}};"
    style = """
var style = categories_%s(feature, value, size, resolution, labelText,
                          labelFont, labelFill)""" % sln
    value = getValue(layer, renderer)
    return (style, pattern, setPattern, value, defs, useAnyMapUnits)
Esempio n. 7
0
def singleSymbol(renderer, stylesFolder, layer_alpha, sln, legendFolder,
                 layer):
    symbol = renderer.symbol()
    (style, pattern, setPattern,
     useMapUnits) = getSymbolAsStyle(symbol, stylesFolder, layer_alpha,
                                     renderer, sln, layer)
    style = "var style = " + style
    legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(symbol, QSize(16, 16))
    legendIcon.save(os.path.join(legendFolder, sln + ".png"))
    value = 'var value = ""'
    return (style, pattern, setPattern, value, useMapUnits)
Esempio n. 8
0
def singleSymbol(renderer, stylesFolder, layer_alpha, sln, legendFolder,
                 layer):
    symbol = renderer.symbol()
    (style, pattern, setPattern,
     useMapUnits) = getSymbolAsStyle(symbol, stylesFolder,
                                     layer_alpha, renderer, sln, layer)
    style = "var style = " + style
    legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(
        symbol, QSize(16, 16))
    legendIcon.save(os.path.join(legendFolder, sln + ".png"))
    value = 'var value = ""'
    return (style, pattern, setPattern, value, useMapUnits)
def iconLegend(symbol, catr, outputProjectFileName, layerName, catLegend, cnt):
    try:
        iconSize = (symbol.size() * 4) + 5
    except Exception:
        iconSize = 16
    legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(
        symbol, QSize(iconSize, iconSize))
    safeLabel = re.sub(r'[\W_]+', '', catr.label()) + str(cnt)
    legendIcon.save(
        os.path.join(outputProjectFileName, "legend",
                     layerName + "_" + safeLabel + ".png"))
    catLegend += """<tr><td style="text-align: center;"><img src="legend/"""
    catLegend += layerName + "_" + safeLabel + """.png" /></td><td>"""
    catLegend += catr.label().replace("'", "\\'") + "</td></tr>"
    return catLegend
Esempio n. 10
0
def iconLegend(symbol, catr, outputProjectFileName, layerName, catLegend, cnt):
    try:
        iconSize = (symbol.size() * 4) + 5
    except:
        iconSize = 16
    legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(symbol,
                                                         QSize(iconSize,
                                                               iconSize))
    safeLabel = re.sub(r'[\W_]+', '', catr.label()) + unicode(cnt)
    legendIcon.save(os.path.join(outputProjectFileName, "legend",
                                 layerName + "_" + safeLabel + ".png"))
    catLegend += """<tr><td style="text-align: center;"><img src="legend/"""
    catLegend += layerName + "_" + safeLabel + """.png" /></td><td>"""
    catLegend += catr.label().replace("'", "\\'") + "</td></tr>"
    return catLegend
Esempio n. 11
0
def graduated(layer, renderer, legendFolder, sln, stylesFolder, layer_alpha):
    cluster = False
    ranges = []
    elseif = ""
    useAnyMapUnits = False
    for cnt, ran in enumerate(renderer.ranges()):
        legendIcon = QgsSymbolLayerUtils.symbolPreviewPixmap(
            ran.symbol(), QSize(16, 16))
        legendIcon.save(os.path.join(
            legendFolder, sln + "_" + unicode(cnt) + ".png"))
        (symbolstyle, pattern, setPattern,
         useMapUnits) = getSymbolAsStyle(ran.symbol(), stylesFolder,
                                         layer_alpha, renderer, sln, layer)
        ranges.append("""%sif (value >= %f && value <= %f) {
            style = %s
                    }""" % (elseif, ran.lowerValue(), ran.upperValue(),
                            symbolstyle))
        elseif = " else "
        if useMapUnits:
            useAnyMapUnits = True
    style = "".join(ranges)
    value = getValue(layer, renderer)
    return (style, pattern, setPattern, value, useAnyMapUnits)
Esempio n. 12
0
def pixmapForLegendNode(legend_node):

    # handles only symbol nodes
    if not isinstance(legend_node, QgsSymbolLegendNode):
        return

    # If size is default, use default implementation
    size = iface.layerTreeView().iconSize()
    if size.width() in (-1, 16):
        size = QSize(18, 18)

    symbol = legend_node.symbol()
    if not symbol:
        return

    # Compute minimum width
    model = iface.layerTreeView().layerTreeModel()
    if not legend_node.layerNode():
        return

    text = legend_node.textOnSymbolLabel()

    minimum_width = max(
        max(
            l_node.minimumIconSize().width() + (8 if text else 0)
            for l_node in model.layerLegendNodes(legend_node.layerNode())
            if isinstance(l_node, QgsSymbolLegendNode)
        ),
        size.width(),
    )

    symbol_size = QSize(minimum_width, size.height())
    context = QgsRenderContext.fromMapSettings(iface.mapCanvas().mapSettings())
    pixmap = QgsSymbolLayerUtils.symbolPreviewPixmap(symbol, symbol_size, 0, context)

    if text:
        painter = QPainter(pixmap)
        text_format = legend_node.textOnSymbolTextFormat()

        try:
            text_context = createTemporaryRenderContext()
            if text_context:
                painter.setRenderHint(QPainter.Antialiasing)
                text_context.setPainter(painter)

                font_metrics = QFontMetricsF(text_format.scaledFont(context))
                y_baseline_v_center = (
                    symbol_size.height()
                    + font_metrics.ascent()
                    - font_metrics.descent()
                ) / 2

                QgsTextRenderer.drawText(
                    QPointF(symbol_size.width() / 2, y_baseline_v_center),
                    0,
                    QgsTextRenderer.AlignCenter,
                    [text],
                    text_context,
                    text_format,
                )
                text_context.setPainter(None)

        except Exception as e:
            QgsMessageLog.logMessage(str(e))

    return pixmap