Graphics Reference
In-Depth Information
We're now ready to define the method that draws the contents of the layer. As you might
imagine, this method is called draw() . Let's start by obtaining the QPainter object
we'll use to do the actual drawing:
def draw(self, renderContext):
painter = renderContext.painter()
Next, we want to find the portion of the Earth's surface that is currently visible:
extent = renderContext.extent()
This gives us the portion of the grid that we want to draw. To make sure the grid lines are
on whole degrees of latitude and longitude, we round the extent up and down to the
nearest whole number, like this:
xMin = int(math.floor(extent.xMinimum()))
xMax = int(math.ceil(extent.xMaximum()))
yMin = int(math.floor(extent.yMinimum()))
yMax = int(math.ceil(extent.yMaximum()))
Next, we need to set up the painter to draw the grid lines:
pen = QPen()
pen.setColor(QColor("light gray"))
pen.setWidth(1.0)
painter.setPen(pen)
Now, we're almost ready to start drawing the grid. To draw the grid lines, though, we'll
need some way of translating between latitude/longitude values and pixel coordinates on
the computer screen. We'll do this using a QgsMapToPixel object, which we can get
from the rendering context:
mapToPixel = renderContext.mapToPixel()
Now, we're finally ready to draw the grid lines. Let's start by drawing a vertical grid line
on each whole degree of longitude:
for x in range(xMin, xMax+1):
coord1 = mapToPixel.transform(x, yMin)
coord2 = mapToPixel.transform(x, yMax)
Search WWH ::




Custom Search