I want to create a rotated grid inside a polygon using a starting point and a rotation angle. I have started with the python script found here.
I have altered the original script to accommodate changes to QGIS 3.0 and introduced changes for the rotation and the loops. Obviously, something is amiss since the script is getting stuck in an infinite loop and I have to crash QGIS to stop.
Any idea where I went wrong?
Here is the script:
from qgis.core import *
from qgis.utils import iface
import math
# Set the spacing
spacing = 2.5
rot = math.radians(35.392)
# Set the inset
inset_x = 0
inset_y = 0
# Get the Coordinate Reference System and the extent from the loaded layer
layer = iface.activeLayer() # load the layer as you want
crs = layer.crs().toWkt()
ext=layer.extent()
# Create a new vector point layer
points_layer = QgsVectorLayer('Point?crs=' + crs, 'grid', "memory")
prov = points_layer.dataProvider()
# Create the coordinates of the points in the grid
points = []
for ft in layer.getFeatures():
feat_geom = ft.geometry()
# Set the extent of the new layer
#xmin = ext.xMinimum() + inset_x
xmin = 755358.66
xmax = 755687.28
ymin = ext.yMinimum()
ymax = 3726718.02 # - inset_y
#y = ymax
#y = ymax
xstart = xmax
while xstart >= xmin:
y = ymax
x = xstart
while y >= ymin:
geom = QgsGeometry().fromPointXY(QgsPointXY(x, y))
feat = QgsFeature()
point = QgsPointXY(x,y)
feat.setGeometry(QgsGeometry.fromPointXY(point))
if feat_geom.contains(feat.geometry()):
points.append(feat)
x = x + (spacing * math.cos(rot))
y = y - (spacing * math.sin(rot))
xstart = xstart - spacing * math.cos(rot)
prov.addFeatures(points)
points_layer.updateExtents()
# Add the layer to the map
QgsProject.instance().addMapLayer(points_layer)

y = y - (spacing * math.sin(rot))is inside of second while. I think that it should be out. – xunilk Nov 08 '19 at 00:17