예제 #1
0
    def testSimpleLineWithOffset(self):
        """ test that rendering a polygon with simple line symbol with offset results in closed line"""
        layer = QgsSimpleLineSymbolLayer()
        layer.setOffset(-1)

        symbol = QgsFillSymbol()
        symbol.changeSymbolLayer(0, layer)

        image = QImage(200, 200, QImage.Format_RGB32)
        painter = QPainter()
        ms = QgsMapSettings()

        geom = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0))')
        f = QgsFeature()
        f.setGeometry(geom)

        extent = geom.geometry().boundingBox()
        # buffer extent by 10%
        extent = extent.buffer((extent.height() + extent.width()) / 20.0)

        ms.setExtent(extent)
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI

        painter.begin(image)
        image.fill(QColor(255, 255, 255))

        symbol.startRender(context)
        symbol.renderFeature(f, context)
        symbol.stopRender(context)
        painter.end()

        self.assertTrue(self.imageCheck('symbol_layer', 'fill_simpleline_offset', image))
예제 #2
0
    def testSimpleLineUnitDefault(self):
        symbol = QgsSimpleLineSymbolLayer(QColor("black"), 1)
        symbol.setCustomDashVector([10, 10])
        symbol.setUseCustomDashPattern(True)
        symbol.setOffset(5)
        dom, root = self.symbolToSld(symbol)

        # print ("Simple line px: \n" + dom.toString())

        self.assertStrokeWidth(root, 1, 4)
        self.assertDashPattern(root, 4, '36 36')
        self.assertStaticPerpendicularOffset(root, '18')
예제 #3
0
    def testSimpleLineUnitPixel(self):
        symbol = QgsSimpleLineSymbolLayer(QColor("black"), 1)
        symbol.setCustomDashVector([10, 10])
        symbol.setUseCustomDashPattern(True)
        symbol.setOffset(5)
        symbol.setOutputUnit(QgsUnitTypes.RenderPixels)
        dom, root = self.symbolToSld(symbol)

        # print ("Simple line px: \n" + dom.toString())

        self.assertStrokeWidth(root, 1, 1)
        self.assertDashPattern(root, 4, '10 10')
        self.assertStaticPerpendicularOffset(root, '5')
예제 #4
0
    def testSimpleLineWithOffset(self):
        """ test that rendering a simple line symbol with offset"""
        layer = QgsSimpleLineSymbolLayer(QColor(0, 0, 0))
        layer.setOffset(1)

        symbol = QgsLineSymbol()
        symbol.changeSymbolLayer(0, layer)

        image = QImage(200, 200, QImage.Format_RGB32)
        painter = QPainter()
        ms = QgsMapSettings()

        geom = QgsGeometry.fromWkt('LineString (0 0, 10 0, 10 10, 0 10, 0 0)')
        f = QgsFeature()
        f.setGeometry(geom)

        extent = geom.constGet().boundingBox()
        # buffer extent by 10%
        extent = extent.buffered((extent.height() + extent.width()) / 20.0)

        ms.setExtent(extent)
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI

        painter.begin(image)
        image.fill(QColor(255, 255, 255))

        symbol.startRender(context)
        symbol.renderFeature(f, context)
        symbol.stopRender(context)
        painter.end()

        self.assertTrue(
            self.imageCheck('symbol_layer', 'simpleline_offset', image))
예제 #5
0
    def testCondenseFillAndOutline(self):
        """
        Test QgsSymbolLayerUtils.condenseFillAndOutline
        """
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            None, None))

        # not simple fill or line
        self.assertFalse(
            QgsSymbolLayerUtils.condenseFillAndOutline(
                QgsShapeburstFillSymbolLayer(), QgsSimpleLineSymbolLayer()))
        self.assertFalse(
            QgsSymbolLayerUtils.condenseFillAndOutline(
                QgsSimpleFillSymbolLayer(), QgsMarkerLineSymbolLayer()))

        # simple fill/line
        fill = QgsSimpleFillSymbolLayer()
        line = QgsSimpleLineSymbolLayer()

        # set incompatible settings on outline
        line.setUseCustomDashPattern(True)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setDashPatternOffset(1)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setAlignDashPattern(True)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setTweakDashPatternOnCorners(True)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setTrimDistanceStart(1)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setTrimDistanceEnd(1)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setDrawInsidePolygon(True)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setRingFilter(QgsSimpleLineSymbolLayer.ExteriorRingOnly)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setOffset(1)
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        line = QgsSimpleLineSymbolLayer()
        line.setDataDefinedProperty(QgsSymbolLayer.PropertyTrimEnd,
                                    QgsProperty.fromValue(4))
        self.assertFalse(QgsSymbolLayerUtils.condenseFillAndOutline(
            fill, line))

        # compatible!
        line = QgsSimpleLineSymbolLayer()
        line.setColor(QColor(255, 0, 0))
        line.setWidth(1.2)
        line.setWidthUnit(QgsUnitTypes.RenderPoints)
        line.setWidthMapUnitScale(QgsMapUnitScale(1, 2))
        line.setPenJoinStyle(Qt.MiterJoin)
        line.setPenStyle(Qt.DashDotDotLine)
        self.assertTrue(QgsSymbolLayerUtils.condenseFillAndOutline(fill, line))

        self.assertEqual(fill.strokeColor(), QColor(255, 0, 0))
        self.assertEqual(fill.strokeWidth(), 1.2)
        self.assertEqual(fill.strokeWidthUnit(), QgsUnitTypes.RenderPoints)
        self.assertEqual(fill.strokeWidthMapUnitScale(), QgsMapUnitScale(1, 2))
        self.assertEqual(fill.penJoinStyle(), Qt.MiterJoin)
        self.assertEqual(fill.strokeStyle(), Qt.DashDotDotLine)
예제 #6
0
파일: Network.py 프로젝트: R4GIS/QTRANUS
    def editNetworkLayer(self, progressBar, layerName, scenariosExpression,
                         networkExpression, variable, level, projectPath,
                         group, networkLinkShapePath, method, layerId,
                         expressionNetworkText, color):
        """
            @summary: Get operators dictionary
            @param layerName: Layer name
            @type layerName: String
            @param scenariosExpression: Scenarios expression
            @type scenariosExpression: Stack object
            @param networkExpression: Network expression
            @type networkExpression: Stack object
            @param variable: Variable to evaluate
            @type variable: String
            @param level: Level to evaluate (Total, Routes, Operators)
            @type level: Level object
            @param projectPath: Project path
            @type projectPath: String
            @param group: Project group
            @type group: Layer group
            @param networkLinkShapePath: Network link shape path
            @type networkLinkShapePath: String
            @return: Result of the layer creation
        """

        if scenariosExpression is None:
            QMessageBox.warning(None, "Network expression",
                                "There is not scenarios information.")
            print("There is not scenarios information.")
            return False

        registry = QgsProject.instance()
        layersCount = len(registry.mapLayers())
        result, resultData, minValue, maxValue = self.network_data_access.create_network_memory(
            layerName, scenariosExpression, networkExpression, variable, level,
            projectPath)
        progressBar.setValue(15)

        if result:
            # Source shape, name of the new shape, providerLib
            layer = QgsVectorLayer(networkLinkShapePath,
                                   layerName + "_network", 'ogr')
            epsg = layer.crs().postgisSrid()
            intMethod = 0 if method == "Color" else 1
            rowCounter = len(resultData)

            if not layer.isValid():
                return False

            feats = [feat for feat in layer.getFeatures()]

            # Create a vector layer with data on Memory
            memoryLayer = registry.mapLayer(layerId)

            memory_data = memoryLayer.dataProvider()
            joinedFieldName = "Result"
            shpField = "Id"
            attr = layer.dataProvider().fields().toList()
            attr += [QgsField(joinedFieldName, QVariant.Double)]
            progressBar.setValue(25)

            memory_data.addAttributes(attr)
            memory_data.addFeatures(feats)

            num = 30
            progressBar.setValue(num)
            progressInterval = 70 / len(resultData)

            memoryLayer.startEditing()
            for rowItem in np.nditer(resultData):
                value = 0
                num += progressInterval
                progressBar.setValue(num)

                it = memoryLayer.getFeatures("LINKID  = '{0}'".format(
                    str(rowItem['Id']).replace("b", "").replace("'", "")))
                for id_feature in it:
                    memoryLayer.changeAttributeValue(
                        id_feature.id(),
                        memory_data.fieldNameIndex(joinedFieldName),
                        QVariant(round(float(rowItem['Result']), 2)))

            memoryLayer.commitChanges()

            myStyle = QgsStyle().defaultStyle()
            defaultColorRampNames = myStyle.colorRampNames()
            ramp = myStyle.colorRamp(defaultColorRampNames[0])
            ranges = []
            nCats = ramp.count()
            rng = maxValue - minValue
            nCats = 8
            scale = QgsMapUnitScale(minValue, maxValue)

            if method == "Color":
                color1 = list(
                    map(lambda x: int(x), color['color1'].split(",")[0:3]))
                color2 = list(
                    map(lambda x: int(x), color['color2'].split(",")[0:3]))
                interpolatedColors = HP.linear_gradient(color1, color2, nCats)

            for i in range(0, nCats):
                v0 = minValue + rng / float(nCats) * i
                v1 = minValue + rng / float(nCats) * (i + 1)
                if method == "Color":
                    line = QgsSimpleLineSymbolLayer(
                        QColor(interpolatedColors['r'][i],
                               interpolatedColors['g'][i],
                               interpolatedColors['b'][i]))
                    line.setOffsetUnit(2)
                    line.setOffset(2)
                    line.setWidth(0.8)
                    symbol = QgsLineSymbol()
                    symbol.changeSymbolLayer(0, line)
                    myRange = QgsRendererRange(v0, v1, symbol, "")

                elif method == "Size":
                    qcolor = QColor()
                    qcolor.setRgb(color)
                    line = QgsSimpleLineSymbolLayer(qcolor)
                    line.setOffsetUnit(2)
                    line.setOffset(0.7)
                    # Symbol
                    # symbolLine = QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.ArrowHead)
                    # Mark line
                    # markLine = QgsMarkerLineSymbolLayer()
                    # markLine.setPlacement(4)
                    symbolo = QgsLineSymbol()
                    symbolo.changeSymbolLayer(0, line)
                    # symbolo.appendSymbolLayer(line)
                    myRange = QgsRendererRange(v0, v1, symbolo, "")
                ranges.append(myRange)

            # The first parameter refers to the name of the field that contains the calculated value (expression)
            modeRender = QgsGraduatedSymbolRenderer.Mode(2)
            renderer = QgsGraduatedSymbolRenderer(joinedFieldName, ranges)
            renderer.setMode(modeRender)
            renderer.setGraduatedMethod(intMethod)

            if method == "Size":
                renderer.setSymbolSizes(0.200000, 2.60000)

            renderer.setSourceColorRamp(ramp)
            memoryLayer.setRenderer(renderer)

            typeLayer = "network"
            fieldName = "LINKID"
            networkExpressionText = str(scenariosExpression)

            # Create XML File ".qtranus" with the parameters of the executions
            if FileMXML.if_exist_xml_layers(projectPath):
                if FileMXML.if_exist_layer(projectPath, memoryLayer.id()):
                    FileMXML.update_xml_file(memoryLayer.name(),
                                             memoryLayer.id(),
                                             scenariosExpression, variable,
                                             networkExpression, projectPath,
                                             expressionNetworkText, method,
                                             level, color)
                else:
                    FileMXML.add_layer_xml_file(memoryLayer.name(),
                                                memoryLayer.id(),
                                                scenariosExpression, variable,
                                                networkExpression, projectPath,
                                                expressionNetworkText,
                                                shpField, typeLayer, method,
                                                level, color)
            else:
                FileMXML.create_xml_file(memoryLayer.name(), memoryLayer.id(),
                                         scenariosExpression, variable,
                                         networkExpression, projectPath,
                                         expressionNetworkText, shpField,
                                         typeLayer, method, level, color)

            #group.insertLayer((layersCount+1), memoryLayer)
            progressBar.setValue(100)

        return True