コード例 #1
0
def append_SimpleFillSymbolLayer(symbol, layer):
    """
    Appends a SimpleFillSymbolLayer to a symbol
    """
    fill_color = symbol_color_to_qcolor(layer.color)
    out = QgsSimpleFillSymbolLayer(fill_color)
    out.setEnabled(layer.enabled)
    out.setLocked(layer.locked)

    if layer.outline_layer:
        if isinstance(layer.outline_layer,
                      (SimpleLineSymbolLayer, CartographicLineSymbolLayer)):
            out.setStrokeColor(
                symbol_color_to_qcolor(layer.outline_layer.color))
            out.setStrokeWidth(points_to_mm(layer.outline_layer.width))
        if isinstance(layer.outline_layer, SimpleLineSymbolLayer):
            out.setStrokeStyle(
                symbol_pen_to_qpenstyle(layer.outline_layer.line_type))
        if isinstance(layer.outline_layer, CartographicLineSymbolLayer):
            out.setPenJoinStyle(
                symbol_pen_to_qpenjoinstyle(layer.outline_layer.join))
        # better matching of null stroke color to QGIS symbology
        if out.strokeColor().alpha() == 0:
            out.setStrokeStyle(Qt.NoPen)

        # todo - change to new symbol layer if outline offset set
        symbol.appendSymbolLayer(out)
    else:
        # outline is a symbol itself
        out.setStrokeStyle(Qt.NoPen)
        symbol.appendSymbolLayer(out)

        # get all layers from outline
        append_SymbolLayer_to_QgsSymbolLayer(symbol, layer.outline_symbol)
コード例 #2
0
    def testCategorizedPolys(self):
        source = QgsVectorLayer(os.path.join(TEST_DATA_DIR, 'polys_overlapping_with_cat.shp'))
        self.assertTrue(source.isValid())
        map_settings = QgsMapSettings()
        map_settings.setExtent(source.extent())
        map_settings.setDestinationCrs(source.crs())
        map_settings.setLayers([source])

        layer = QgsSimpleFillSymbolLayer()
        layer.setStrokeColor(QColor(0, 0, 0))
        layer.setStrokeWidth(1)
        layer.setColor(QColor(200, 250, 50, 150))
        symbol1 = QgsFillSymbol()
        symbol1.changeSymbolLayer(0, layer)

        layer = QgsSimpleFillSymbolLayer()
        layer.setStrokeColor(QColor(0, 0, 0))
        layer.setStrokeWidth(1)
        layer.setColor(QColor(50, 250, 200, 150))
        symbol2 = QgsFillSymbol()
        symbol2.changeSymbolLayer(0, layer)

        sub_renderer = QgsCategorizedSymbolRenderer('cat', [QgsRendererCategory('cat1', symbol1, 'cat1'),
                                                            QgsRendererCategory('cat2', symbol2, 'cat2')
                                                            ])
        source.setRenderer(QgsMergedFeatureRenderer(sub_renderer))

        self.assertTrue(self.imageCheck('polys_categorizedrenderer', 'polys_categorizedrenderer', map_settings))
コード例 #3
0
def SimpleFillSymbolLayer_to_QgsSimpleFillSymbolLayer(layer):
    """
    Converts a SimpleFillSymbolLayer to a QgsSimpleFillSymbolLayer
    """
    fill_color = symbol_color_to_qcolor(layer.color)
    out = QgsSimpleFillSymbolLayer(fill_color)

    if layer.outline_layer:
        if isinstance(layer.outline_layer,
                      (SimpleLineSymbolLayer, CartographicLineSymbolLayer)):
            out.setStrokeColor(
                symbol_color_to_qcolor(layer.outline_layer.color))
            out.setStrokeWidth(points_to_mm(layer.outline_layer.width))
        if isinstance(layer.outline_layer, SimpleLineSymbolLayer):
            out.setStrokeStyle(
                symbol_pen_to_qpenstyle(layer.outline_layer.line_type))
        if isinstance(layer.outline_layer, CartographicLineSymbolLayer):
            out.setPenJoinStyle(
                symbol_pen_to_qpenjoinstyle(layer.outline_layer.join))
        # better matching of null stroke color to QGIS symbology
        if out.strokeColor().alpha() == 0:
            out.setStrokeStyle(Qt.NoPen)

        # todo - change to new symbol layer if outline offset set
    else:
        # todo - outline symbol layer
        raise NotImplementedException('Outline symbol layer not implemented')

    return out
コード例 #4
0
    def testReadWriteSettings(self):
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        fill = QgsSimpleFillSymbolLayer()
        fill_symbol = QgsFillSymbol()
        fill_symbol.changeSymbolLayer(0, fill)
        fill.setColor(Qt.green)
        fill.setStrokeColor(Qt.red)
        fill.setStrokeWidth(6)

        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        page.setPageStyleSymbol(fill_symbol.clone())
        self.assertEqual(collection.pageNumber(page), -1)
        collection.addPage(page)

        # add a second page
        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        fill_symbol.setColor(Qt.blue)
        page2.setPageStyleSymbol(fill_symbol.clone())
        collection.addPage(page2)

        doc = QDomDocument("testdoc")
        elem = doc.createElement("test")
        self.assertTrue(collection.writeXml(elem, doc, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        collection2 = l2.pageCollection()

        self.assertTrue(
            collection2.readXml(elem.firstChildElement(), doc,
                                QgsReadWriteContext()))

        self.assertEqual(collection2.pageCount(), 2)

        self.assertEqual(
            collection2.page(0).pageStyleSymbol().symbolLayer(
                0).color().name(), '#00ff00')
        self.assertEqual(
            collection2.page(0).pageStyleSymbol().symbolLayer(
                0).strokeColor().name(), '#ff0000')

        self.assertEqual(
            collection2.page(1).pageStyleSymbol().symbolLayer(
                0).color().name(), '#0000ff')
        self.assertEqual(
            collection2.page(1).pageStyleSymbol().symbolLayer(
                0).strokeColor().name(), '#ff0000')
コード例 #5
0
    def testSymbol(self):
        """
        Test setting a page symbol for the collection
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()
        self.assertTrue(collection.pageStyleSymbol())

        fill = QgsSimpleFillSymbolLayer()
        fill_symbol = QgsFillSymbol()
        fill_symbol.changeSymbolLayer(0, fill)
        fill.setColor(Qt.green)
        fill.setStrokeColor(Qt.red)
        fill.setStrokeWidth(6)
        collection.setPageStyleSymbol(fill_symbol)
        self.assertEqual(collection.pageStyleSymbol().symbolLayer(0).color().name(), '#00ff00')
        self.assertEqual(collection.pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')
コード例 #6
0
    def testSymbol(self):
        """
        Test setting a page symbol for the collection
        """
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()
        self.assertTrue(collection.pageStyleSymbol())

        fill = QgsSimpleFillSymbolLayer()
        fill_symbol = QgsFillSymbol()
        fill_symbol.changeSymbolLayer(0, fill)
        fill.setColor(Qt.green)
        fill.setStrokeColor(Qt.red)
        fill.setStrokeWidth(6)
        collection.setPageStyleSymbol(fill_symbol)
        self.assertEqual(collection.pageStyleSymbol().symbolLayer(0).color().name(), '#00ff00')
        self.assertEqual(collection.pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')
コード例 #7
0
    def testDefaults(self):
        p = QgsProject()
        l = QgsLayout(p)
        p = QgsLayoutItemPage(l)
        self.assertTrue(p.pageStyleSymbol())

        fill = QgsSimpleFillSymbolLayer()
        fill_symbol = QgsFillSymbol()
        fill_symbol.changeSymbolLayer(0, fill)
        fill.setColor(Qt.green)
        fill.setStrokeColor(Qt.red)
        fill.setStrokeWidth(6)
        p.setPageStyleSymbol(fill_symbol)

        self.assertEqual(p.pageStyleSymbol().symbolLayer(0).color().name(),
                         '#00ff00')
        self.assertEqual(
            p.pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')
コード例 #8
0
    def testSinglePolys(self):
        source = QgsVectorLayer(os.path.join(TEST_DATA_DIR, 'polys_overlapping.shp'))
        self.assertTrue(source.isValid())
        map_settings = QgsMapSettings()
        map_settings.setExtent(source.extent())
        map_settings.setDestinationCrs(source.crs())
        map_settings.setLayers([source])

        layer = QgsSimpleFillSymbolLayer()
        layer.setStrokeColor(QColor(0, 0, 0))
        layer.setStrokeWidth(1)
        layer.setColor(QColor(200, 250, 50))
        symbol = QgsFillSymbol([layer])

        sub_renderer = QgsSingleSymbolRenderer(symbol)
        source.setRenderer(QgsMergedFeatureRenderer(sub_renderer))

        self.assertTrue(self.imageCheck('single_subrenderer', 'single_subrenderer', map_settings))
コード例 #9
0
    def testReadWriteXml(self):
        p = QgsProject()
        l = QgsLayout(p)
        collection = l.pageCollection()

        fill = QgsSimpleFillSymbolLayer()
        fill_symbol = QgsFillSymbol()
        fill_symbol.changeSymbolLayer(0, fill)
        fill.setColor(Qt.green)
        fill.setStrokeColor(Qt.red)
        fill.setStrokeWidth(6)
        collection.setPageStyleSymbol(fill_symbol)

        # add a page
        page = QgsLayoutItemPage(l)
        page.setPageSize('A4')
        self.assertEqual(collection.pageNumber(page), -1)

        collection.addPage(page)

        # add a second page
        page2 = QgsLayoutItemPage(l)
        page2.setPageSize('A5')
        collection.addPage(page2)

        doc = QDomDocument("testdoc")
        elem = doc.createElement("test")
        self.assertTrue(collection.writeXml(elem, doc, QgsReadWriteContext()))

        l2 = QgsLayout(p)
        collection2 = l2.pageCollection()

        self.assertTrue(collection2.readXml(elem.firstChildElement(), doc, QgsReadWriteContext()))

        self.assertEqual(collection2.pageCount(), 2)
        self.assertEqual(collection2.page(0).pageSize().width(), 210)
        self.assertEqual(collection2.page(0).pageSize().height(), 297)
        self.assertEqual(collection2.page(1).pageSize().width(), 148)
        self.assertEqual(collection2.page(1).pageSize().height(), 210)

        self.assertEqual(collection2.pageStyleSymbol().symbolLayer(0).color().name(), '#00ff00')
        self.assertEqual(collection2.pageStyleSymbol().symbolLayer(0).strokeColor().name(), '#ff0000')
コード例 #10
0
    def styleCreator(self, feature_geometry, layer_bound, utmSRID, id_attr,
                     id_value, spacing, crossX, crossY, scale, fontSize, font,
                     fontLL, llcolor, linwidth_geo, linwidth_utm,
                     linwidth_buffer_geo, linwidth_buffer_utm, geo_grid_color,
                     utm_grid_color, geo_grid_buffer_color,
                     utm_grid_buffer_color, masks_check):
        """Getting Input Data For Grid Generation"""
        linwidth_buffer_utm += linwidth_utm
        linwidth_buffer_geo += linwidth_geo
        grid_spacing = spacing
        geo_number_x = crossX
        geo_number_y = crossY
        fSize = fontSize
        fontType = font
        LLfontType = fontLL

        #Defining CRSs Transformations
        trLLUTM = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:4326'),
            QgsCoordinateReferenceSystem('EPSG:' + str(utmSRID)),
            QgsProject.instance())
        trUTMLL = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:' + str(utmSRID)),
            QgsCoordinateReferenceSystem('EPSG:4326'), QgsProject.instance())

        #Transforming to Geographic and defining bounding boxes
        feature_bbox = feature_geometry.boundingBox()
        bound_UTM_bb = str(feature_bbox).replace(',', '').replace('>', '')
        feature_geometry.transform(trUTMLL)
        feature_geo_bbox = feature_geometry.boundingBox()
        feature_bbox_or = feature_geometry.orientedMinimumBoundingBox()
        geo_bound_bb = str(feature_geo_bbox).replace(',', '').replace('>', '')
        oriented_geo_bb = str(feature_bbox_or).replace(',', '').replace(
            '>', '').replace('((', '').replace('))', '')

        #Defining UTM Grid Symbology Type
        properties = {'color': 'black'}
        grid_symb = QgsFillSymbol.createSimple(properties)
        """ Creating UTM Grid """
        extentsUTM = (float(bound_UTM_bb.split()[1]),
                      float(bound_UTM_bb.split()[2]),
                      float(bound_UTM_bb.split()[3]),
                      float(bound_UTM_bb.split()[4]))
        extentsGeo = (float(geo_bound_bb.split()[1]),
                      float(geo_bound_bb.split()[2]),
                      float(geo_bound_bb.split()[3]),
                      float(geo_bound_bb.split()[4]))
        if grid_spacing > 0:
            UTM_num_x = floor(extentsUTM[2] / grid_spacing) - floor(
                extentsUTM[0] / grid_spacing)
            UTM_num_y = floor(extentsUTM[3] / grid_spacing) - floor(
                extentsUTM[1] / grid_spacing)

            if linwidth_buffer_utm != linwidth_utm:
                #Generating Buffer Vertical Lines
                for x in range(1, UTM_num_x + 1):
                    grid_symb = self.utm_Symb_Generator(
                        utmSRID, grid_spacing, trUTMLL, trLLUTM, grid_symb,
                        properties, UTM_num_x, UTM_num_y, x, 0, extentsGeo,
                        extentsUTM, linwidth_buffer_utm, utm_grid_buffer_color)

                #Generating Buffer Horizontal Lines
                for y in range(1, UTM_num_y + 1):
                    grid_symb = self.utm_Symb_Generator(
                        utmSRID, grid_spacing, trUTMLL, trLLUTM, grid_symb,
                        properties, UTM_num_x, UTM_num_y, 0, y, extentsGeo,
                        extentsUTM, linwidth_buffer_utm, utm_grid_buffer_color)

            #Generating Vertical Lines
            for x in range(1, UTM_num_x + 1):
                grid_symb = self.utm_Symb_Generator(
                    utmSRID, grid_spacing, trUTMLL, trLLUTM, grid_symb,
                    properties, UTM_num_x, UTM_num_y, x, 0, extentsGeo,
                    extentsUTM, linwidth_utm, utm_grid_color)

            #Generating Horizontal Lines
            for y in range(1, UTM_num_y + 1):
                grid_symb = self.utm_Symb_Generator(
                    utmSRID, grid_spacing, trUTMLL, trLLUTM, grid_symb,
                    properties, UTM_num_x, UTM_num_y, 0, y, extentsGeo,
                    extentsUTM, linwidth_utm, utm_grid_color)
        """ Creating Geo Grid """
        px = (round(extentsGeo[2], 6) -
              round(extentsGeo[0], 6)) / (geo_number_x + 1)
        py = (round(extentsGeo[3], 6) -
              round(extentsGeo[1], 6)) / (geo_number_y + 1)
        if linwidth_buffer_geo != linwidth_geo:
            grid_symb = self.geoGridcreator(utmSRID, grid_symb, extentsGeo, px,
                                            py, geo_number_x, geo_number_y,
                                            scale, trLLUTM,
                                            linwidth_buffer_geo,
                                            geo_grid_buffer_color)
        grid_symb = self.geoGridcreator(utmSRID, grid_symb, extentsGeo, px, py,
                                        geo_number_x, geo_number_y, scale,
                                        trLLUTM, linwidth_geo, geo_grid_color)
        """ Rendering UTM and Geographic Grid """
        #Changing UTM Grid Color
        grid_symb.deleteSymbolLayer(0)

        #Creating Rule Based Renderer (Rule For The Selected Feature, Root Rule)
        symb_new = QgsRuleBasedRenderer.Rule(grid_symb)
        symb_new.setFilterExpression('\"' + str(id_attr) + '\" = ' +
                                     str(id_value))
        symb_new.setLabel('layer')

        #Appending rules to symbol root rule
        root_symbol_rule = QgsRuleBasedRenderer.Rule(None)
        root_symbol_rule.setFilterExpression('')
        root_symbol_rule.appendChild(symb_new)

        #Applying New Renderer
        render_base = QgsRuleBasedRenderer(root_symbol_rule)
        layer_bound.setRenderer(render_base)
        """Rendering outside area"""
        #Duplicating original layer
        layers_names = [
            i.name() for i in QgsProject.instance().mapLayers().values()
        ]
        if (layer_bound.name() + "_outside") not in layers_names:
            outside_bound_layer = QgsVectorLayer(
                layer_bound.source(),
                layer_bound.name() + "_outside", layer_bound.providerType())
            if layer_bound.providerType() == 'memory':
                feats = [feat for feat in layer_bound.getFeatures()]
                outside_bound_layer_data = outside_bound_layer.dataProvider()
                outside_bound_layer_data.addFeatures(feats)
            QgsProject.instance().addMapLayer(outside_bound_layer)
        else:
            outside_bound_layer = QgsProject.instance().mapLayersByName(
                layer_bound.name() + "_outside")[0]

        #Creating Rule Based Renderer (Rule For The Other Features)
        properties = {'color': 'white'}
        ext_grid_symb = QgsFillSymbol.createSimple(properties)
        symb_out = QgsSimpleFillSymbolLayer()
        symb_out.setFillColor(QColor('white'))
        symb_out.setStrokeWidth(linwidth_utm)
        ext_grid_symb.changeSymbolLayer(0, symb_out)
        rule_out = QgsRuleBasedRenderer.Rule(ext_grid_symb)
        rule_out.setFilterExpression('\"' + str(id_attr) + '\" = ' +
                                     str(id_value))
        rule_out.setLabel('outside')

        root_symbol_rule_out = QgsRuleBasedRenderer.Rule(None)
        root_symbol_rule_out.appendChild(rule_out)

        render_base_out = QgsRuleBasedRenderer(root_symbol_rule_out)
        new_renderer = QgsInvertedPolygonRenderer.convertFromRenderer(
            render_base_out)
        outside_bound_layer.setRenderer(new_renderer)
        """ Labeling Geo Grid """
        dx = [2.0, -11.0, -8.0, -3.6]
        dx = [i * scale * fSize / 1.5 for i in dx]
        dy = [1.7, -3.8, -0.8, -0.8]
        dy = [i * scale * fSize / 1.5 for i in dy]

        root_rule = self.geoGridlabelPlacer(extentsGeo, px, py, geo_number_x,
                                            geo_number_y, dx, dy, fSize,
                                            LLfontType, trLLUTM, llcolor,
                                            scale, layer_bound, trUTMLL)
        """ Labeling UTM Grid"""
        dx = [-2.9, -2.9, -8.9, 2.0]
        dx = [i * scale * fSize / 1.5 for i in dx]
        dy = [1.4, -4.6, -0.5, -1.5]
        dy = [i * scale * fSize / 1.5 for i in dy]
        dy0 = [5.0, -7.2, -3.2, -4.2]
        dy0 = [i * scale * fSize / 1.5 for i in dy0]
        dy1 = [2.15, 1.2]
        dy1 = [i * scale * fSize / 1.5 for i in dy1]

        root_rule = self.utmGridlabelPlacer(root_rule, grid_spacing,
                                            extentsGeo, extentsUTM, px, py,
                                            UTM_num_x, UTM_num_y, trUTMLL,
                                            trLLUTM, dx, dy, dy0, dy1, fSize,
                                            fontType, scale, oriented_geo_bb,
                                            layer_bound)
        """ Activating Labels """
        rules = QgsRuleBasedLabeling(root_rule)
        layer_bound.setLabeling(rules)
        layer_bound.setLabelsEnabled(True)

        if masks_check:
            self.apply_masks(layer_bound)

        layer_bound.triggerRepaint()

        return
コード例 #11
0
ファイル: qisoval.py プロジェクト: sigeal/qisoval
    def btnLaunchAction(self):
        """btnLaunch action"""

        # Paramètres du web service IGN de calcul d'isochrone
        x = 2.424626
        y = 48.845793
        location = '{},{}'.format(x, y)
        method = 'time'  # time distance
        graphname = 'Voiture'  # Voiture Pieton
        time = 90 * 60  # si method time
        distance = 100000  # si method distance
        holes = False  # True False
        smoothing = True  # True False
        epsg = 4326
        apiKey = 'choisirgeoportail'

        # Paramètres de symbologie
        fillRed = QColor(251, 154, 153)
        fillBlue = QColor(166, 206, 227)
        fillGreen = QColor(178, 223, 138)
        fillColor = fillGreen
        strokeRed = QColor(251, 154, 153)
        strokeBlue = QColor(31, 120, 180)
        strokeGreen = QColor(51, 160, 44)
        strokeColor = strokeGreen
        borderWidth = 0.4
        opacity = 0.7

        # url du service de calcul
        if method == 'time':
            param = 'time={}'.format(time)
        elif method == 'distance':
            param = 'distance={}'.format(distance)

        url = '''
            https://wxs.ign.fr/{}/isochrone/isochrone.xml?location={}&method={}&graphName={}&exclusions=&{}&holes={}&smoothing={}
        '''.format(apiKey, location, method, graphname, param, holes,
                   smoothing)
        print(url)

        # Récupération du User-Agent QGIS
        s = QgsSettings()
        userAgent = s.value('/qgis/networkAndProxy/userAgent', 'Mozilla/5.0')
        headers = {'User-Agent': userAgent}

        # Appel du service
        #xmlResponse = requests.get(url, timeout=10)
        xmlResponse = requests.get(url, headers=headers)
        print(xmlResponse)

        # Décodage de la réponse et récupération de la géométrie
        root = ElementTree.fromstring(xmlResponse.content)
        wktGeometry = root.find('wktGeometry')
        #print(wktGeometry.text)
        if wktGeometry is not None:

            # Construction de la requête sql
            sql = '''
                select st_geomfromtext('{}', {}) geom
            '''.format(wktGeometry.text, epsg)
            #print(sql)

            # Construction de la couche virtuelle
            if method == 'time':
                libLayer = '{}_{}_minutes'.format(graphname, int(time / 60))
            elif method == 'distance':
                libLayer = '{}_{}_kilometres'.format(graphname,
                                                     int(distance / 1000))
            vLayer = QgsVectorLayer('?query={}'.format(sql), libLayer,
                                    'virtual')
            #symbol = QgsFillSymbol()
            #symbol.setColor(fillColor)
            symbolLayer = QgsSimpleFillSymbolLayer()
            symbolLayer.setStrokeWidth(borderWidth)
            symbolLayer.setStrokeColor(strokeColor)
            symbolLayer.setFillColor(fillColor)
            vLayer.renderer().symbols(QgsRenderContext())[0].changeSymbolLayer(
                0, symbolLayer)
            vLayer.setOpacity(opacity)  # Pour essai
            QgsProject.instance().addMapLayer(vLayer)

        else:
            print('Échec de l\'appel du service')
コード例 #12
0
    def styleCreator(self, layer, index, id_attr, id_value, spacing, crossX,
                     crossY, scale, color, fontSize, font, fontLL, llcolor,
                     utmcheck):
        """Getting Input Data For Grid Generation"""
        grid_spacing = spacing
        geo_number_x = crossX
        geo_number_y = crossY
        fSize = fontSize
        fontType = font
        LLfontType = fontLL

        #Loading feature
        layer_bound = layer
        query = '"' + str(id_attr) + '"=' + str(id_value)
        layer_bound.selectByExpression(query, QgsVectorLayer.SelectBehavior(0))
        feature_bound = layer_bound.selectedFeatures()[0]
        layer_bound.removeSelection()

        #Getting Feature Source CRS and Geometry
        if utmcheck:
            feature_geometry = feature_bound.geometry()
            bound_UTM = layer_bound.crs().authid()
            feature_bbox = feature_geometry.boundingBox()
            bound_UTM_bb = str(feature_bbox).replace(',', '').replace('>', '')
            # Transforming to Geographic
            transform_feature = QgsCoordinateTransform(
                QgsCoordinateReferenceSystem(bound_UTM),
                QgsCoordinateReferenceSystem('EPSG:4674'),
                QgsProject.instance())
            feature_geometry.transform(transform_feature)
            bound_sourcecrs = 'EPSG:4674'
            feature_bbox = feature_geometry.boundingBox()
            feature_bbox_or = feature_geometry.orientedMinimumBoundingBox()
        else:
            feature_geometry = feature_bound.geometry()
            bound_sourcecrs = layer_bound.crs().authid()
            feature_bbox = feature_geometry.boundingBox()
            feature_bbox_or = feature_geometry.orientedMinimumBoundingBox()
        geo_bound_bb = str(feature_bbox).replace(',', '').replace('>', '')
        oriented_geo_bb = str(feature_bbox_or).replace(',', '').replace(
            '>', '').replace('((', '').replace('))', '')

        #Defining CRSs Transformations
        inom = feature_bound[index]
        if inom[0] == 'N':
            bound_UTM = 'EPSG:319' + str(72 + int(inom[3:5]) - 18)
        elif inom[0] == 'S':
            bound_UTM = 'EPSG:319' + str(78 + int(inom[3:5]) - 18)
        else:
            iface.messageBar().pushMessage("Error",
                                           "Invalid index attribute",
                                           level=Qgis.Critical)
            return
        trLLUTM = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem(bound_sourcecrs),
            QgsCoordinateReferenceSystem(bound_UTM), QgsProject.instance())
        trUTMLL = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem(bound_UTM),
            QgsCoordinateReferenceSystem(bound_sourcecrs),
            QgsProject.instance())

        #Defining UTM Grid Symbology Type
        renderer = layer.renderer()
        properties = {'color': 'black'}
        grid_symb = QgsFillSymbol.createSimple(properties)
        symb_out = QgsSimpleFillSymbolLayer()
        symb_out.setStrokeColor(QColor('black'))
        symb_out.setFillColor(QColor('white'))
        symb_out.setStrokeWidth(0.05)
        """ Creating UTM Grid """
        if not utmcheck:
            geo_UTM = feature_bound.geometry()
            geo_UTM.transform(trLLUTM)
            bound_UTM_bb = str(geo_UTM.boundingBox()).replace(',', '').replace(
                '>', '')
        xmin_UTM = float(bound_UTM_bb.split()[1])
        ymin_UTM = float(bound_UTM_bb.split()[2])
        xmax_UTM = float(bound_UTM_bb.split()[3])
        ymax_UTM = float(bound_UTM_bb.split()[4])

        if grid_spacing > 0:
            UTM_num_x = floor(xmax_UTM / grid_spacing) - floor(
                xmin_UTM / grid_spacing)
            UTM_num_y = floor(ymax_UTM / grid_spacing) - floor(
                ymin_UTM / grid_spacing)
            #Generating Vertical Lines
            for x in range(1, UTM_num_x + 1):
                grid_symb = self.utm_symb_generator(
                    grid_spacing, trUTMLL, trLLUTM, grid_symb, properties,
                    geo_number_x, geo_number_y, UTM_num_x, UTM_num_y, x, 0,
                    geo_bound_bb, bound_UTM_bb, utmcheck)
            #Generating Horizontal Lines
            for y in range(1, UTM_num_y + 1):
                grid_symb = self.utm_symb_generator(
                    grid_spacing, trUTMLL, trLLUTM, grid_symb, properties,
                    geo_number_x, geo_number_y, UTM_num_x, UTM_num_y, 0, y,
                    geo_bound_bb, bound_UTM_bb, utmcheck)
        """ Creating Geo Grid """
        grid_symb = self.geoGridcreator(grid_symb, geo_bound_bb, geo_number_x,
                                        geo_number_y, scale, utmcheck, trLLUTM)
        """ Rendering UTM and Geographic Grid """
        #Changing UTM Grid Color
        grid_symb.setColor(color)
        grid_symb.changeSymbolLayer(0, symb_out)
        #Creating Rule Based Renderer (Rule For The Other Features)
        properties = {'color': 'white'}
        ext_grid_symb = QgsFillSymbol.createSimple(properties)
        symb_ot = QgsRuleBasedRenderer.Rule(ext_grid_symb)
        symb_ot.setFilterExpression('\"' + str(id_attr) + '\" <> ' +
                                    str(id_value))
        symb_ot.setLabel('other')
        #Creating Rule Based Renderer (Rule For The Selected Feature, Root Rule)
        symb_new = QgsRuleBasedRenderer.Rule(grid_symb)
        symb_new.setFilterExpression('\"' + str(id_attr) + '\" = ' +
                                     str(id_value))
        symb_new.setLabel('layer')
        symb_new.appendChild(symb_ot)
        #Applying New Renderer
        render_base = QgsRuleBasedRenderer(symb_new)
        new_renderer = QgsInvertedPolygonRenderer.convertFromRenderer(
            render_base)
        layer_bound.setRenderer(new_renderer)
        """ Labeling Geo Grid """
        if utmcheck:
            dx = [
                2 * scale * fSize / 1.5, -13.6 * scale * fSize / 1.5,
                6 * scale * fSize / 1.5
            ]
            dy = [1.7 * scale * fSize / 1.5, -3.8 * scale * fSize / 1.5]
        else:
            dx = [0.000018 * scale, -0.000120 * scale, 0.00005 * scale]
            dy = [0.000015 * scale, -0.000040 * scale]

        root_rule = self.geoGridlabelPlacer(geo_bound_bb, geo_number_x,
                                            geo_number_y, dx, dy, fSize,
                                            LLfontType, trLLUTM, trUTMLL,
                                            llcolor, utmcheck, scale)
        """ Labeling UTM Grid"""
        if utmcheck:
            dx = [-2.7, -9.7, -6.2, 5.4]
            dx = [i * scale * fSize / 1.5 for i in dx]
            dy = [2.5, -1.7, -0.5, -1.5]
            dy = [i * scale * fSize / 1.5 for i in dy]
            dy0 = [5.45, -4.8, -3.2, -4.2]
            dy0 = [i * scale * fSize / 1.5 for i in dy0]
            dy1 = [2.15, 1.2]
            dy1 = [i * scale * fSize / 1.5 for i in dy1]
        else:
            dx = [-0.00003, -0.000107, -0.000070, 0.000060]
            dx = [i * scale * fSize / 1.5 for i in dx]
            dy = [0.000027, 0.000016, -0.000041, -0.000052]
            dy = [i * scale * fSize / 1.5 for i in dy]
            dy0 = [0.0000644, 0.000053, -0.000076, -0.000087]
            dy0 = [i * scale * fSize / 1.5 for i in dy0]
            dy1 = [0.000032, 0.000020]
            dy1 = [i * scale * fSize / 1.5 for i in dy1]

        root_rule = self.utmGridlabelPlacer(
            root_rule, grid_spacing, geo_bound_bb, bound_UTM_bb, geo_number_x,
            geo_number_y, UTM_num_x, UTM_num_y, trUTMLL, trLLUTM, dx, dy, dy0,
            dy1, fSize, fontType, scale, utmcheck, oriented_geo_bb)
        """ Activating Labels """
        rules = QgsRuleBasedLabeling(root_rule)
        layer.setLabeling(rules)
        layer.setLabelsEnabled(True)
        layer.triggerRepaint()
        return
コード例 #13
0
ファイル: qgis.py プロジェクト: zyxgis/slyr
def append_SimpleFillSymbolLayer(
        symbol,  # pylint: disable=too-many-branches
        layer: SimpleFillSymbolLayer,
        context: Context):
    """
    Appends a SimpleFillSymbolLayer to a symbol
    """
    fill_color = symbol_color_to_qcolor(layer.color)
    out = QgsSimpleFillSymbolLayer(fill_color)
    out.setEnabled(layer.enabled)
    out.setLocked(layer.locked)

    if isinstance(layer, SimpleFillSymbolLayer):
        if layer.outline_layer:
            if isinstance(
                    layer.outline_layer,
                (SimpleLineSymbolLayer, CartographicLineSymbolLayer)):
                out.setStrokeColor(
                    symbol_color_to_qcolor(layer.outline_layer.color))
                out.setStrokeWidth(
                    context.convert_size(layer.outline_layer.width))
                out.setStrokeWidthUnit(context.units)
            if isinstance(layer.outline_layer, SimpleLineSymbolLayer):
                out.setStrokeStyle(
                    symbol_pen_to_qpenstyle(layer.outline_layer.line_type))
            if isinstance(layer.outline_layer, CartographicLineSymbolLayer):
                out.setPenJoinStyle(
                    symbol_pen_to_qpenjoinstyle(layer.outline_layer.join))
            # better matching of null stroke color to QGIS symbology
            if out.strokeColor().alpha() == 0:
                out.setStrokeStyle(Qt.NoPen)

            # TODO
            try:
                if layer.outline_layer.offset:
                    raise NotImplementedException(
                        'Fill outline offset not supported')
            except AttributeError:
                pass
            try:
                if layer.outline_layer.template:
                    raise NotImplementedException(
                        'Fill outline template not supported')
            except AttributeError:
                pass
            try:
                if layer.outline_layer.decoration:
                    raise NotImplementedException(
                        'Fill outline decoration not supported')
            except AttributeError:
                pass

            symbol.appendSymbolLayer(out)
        elif layer.outline_symbol:
            # outline is a symbol itself
            out.setStrokeStyle(Qt.NoPen)
            symbol.appendSymbolLayer(out)

            # get all layers from outline
            append_SymbolLayer_to_QgsSymbolLayer(symbol, layer.outline_symbol,
                                                 context)
        else:
            out.setStrokeStyle(Qt.NoPen)
            symbol.appendSymbolLayer(out)
    elif isinstance(layer, ColorSymbol):
        out.setStrokeStyle(Qt.NoPen)
        symbol.appendSymbolLayer(out)