'How to draw a segment with a gradient color?
Alhazred about 12 hours ago
In my application, I have a list of 3D points and I have to draw on a QGraphicsScene the segments connecting them one after the other. Of course, I cannot draw 3D segments on a 2D surface, thus I'm thinking to draw these segments with a gradient color to show the Z difference between the starting and ending points of each segment.
At the moment I draw each segment with a single color based on the Z coordinate of the ending point.
To decide the color, I get the minimum and maximum Z coordinates among all the points, and then I map the value of the current Z to a 0-255 range using a custom function, I use this code to set the segments' color
# current_point[i][2] is the segment's ending point z value
mapped_color = int(self.mapRange(current_point[i][2], z_min, z_max, 0, 255))
# Gives a color between full yellow (high segments) and full blue (low segments)
color = QtGui.QColor(255-mapped_color, 255-mapped_color, mapped_color)
# Add the segment to the scene, p1 and p2 are QPoint set using the x and y coordinates
self.scene.addLine(QtCore.QLine(p1, p2), color)
This is already a result that gives a good 3D look, but I am looking to find a way to improve it by saying
# last_point is updated at each iteration with the last used point (I already have it)
starting_color = int(self.mapRange(last_point[2], z_min, z_max, 0, 255))
ending_color = int(self.mapRange(current_point[i][2], z_min, z_max, 0, 255))
# Now draw the segment using those 2 colors fading from one to the other
Is it possible to achieve that?
Solution 1:[1]
Thanks to @musicamante I've solved using this code
start_mapped_color = self.mapRange(current_position[2], z_min, z_max, 0, 255)
end_mapped_color = self.mapRange(coords[i][2], z_min, self.z_max, 0, 255)
start_color = QtGui.QColor(255-start_mapped_color, 255-start_mapped_color, start_mapped_color)
end_color = QtGui.QColor(255-end_mapped_color, 255-end_mapped_color, end_mapped_color)
gradient = QtGui.QLinearGradient(p1, p2)
gradient.setColorAt(0, start_color)
gradient.setColorAt(1, end_color)
gradient_pen = QtGui.QPen(QtGui.QBrush(gradient), 1)
self.scene.addLine(QtCore.QLine(p1, p2), pen=gradient_pen)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Luigi Caradonna |
