Today’s post was motivated by a question over on gis.stackexchange, basically: How to draw a line with a gradient?
The issue we have to deal with is there is no gradient line style yet … But there are polygon gradient fills. So we can buffer the line and style the buffers. It’s a bit of an exercise in data-defined styling though:
Before creating the buffer layer, we need to add the coordinates of the line start and end node to the line attributes. This is easy to do using the Field Calculator functions
yat, for example
xat(0) for the x coordinate of the start node and
yat(-1) for the y coordinate of the end node.
Then we can buffer the lines and start styling the buffers. As mentioned, we’ll use the Gradient fill Symbol layer type.
The interesting part happens in the Data-defined properties. The start and end colors are computed from the measurement values
to_m. Next, it’s important to use the
feature coordinate mode because this will ensure that the coordinate system for the color gradient is based on the feature extent (with [0,0] in the upper left corner of the feature bbox).
Once that’s set up, we can compute the gradient start and end positions based on the line start and end node locations which we added to the attribute table in the beginning. If you’re wondering why Reference point 1 y is based on
to_y (y coordinate of the line end point) rather than
from_y, it’s due to the difference in coordinate origins in the geometry and the color gradient coordinate space: [0,0] is the lower left corner for the geometries but the upper left corner for the color gradient.
As the title suggests, this is a really hackish solution for gradient line symbols. It will only provide reasonable results for straight – or close to straight – lines. But I’m very confident that we’ll have a real gradient line style in QGIS sooner or later.