mozman / svgwrite

Python Package to write SVG files (UNMAINTAINED)
Other
547 stars 97 forks source link

Gradient stop with offset smaller than the last added is ignored #116

Open GeoffreyCoulaud opened 1 year ago

GeoffreyCoulaud commented 1 year ago

The following code will make a red to blue gradient, ignoring the green gradient stop with offset 0.5

gradient = LinearGradient(start=(0, 0), end=(1, 0))
gradient.add_stop_color(offset=0,   color="#FF0000", opacity=1)
gradient.add_stop_color(offset=1,   color="#0000FF", opacity=1)
gradient.add_stop_color(offset=0.5, color="#00FF00", opacity=1)

I've monkey patched the gradient add method to keep the order, and I confirm it works.

def monkey_patch_gradient_add(self, stop):
    # If no offset given, add as is
    if stop["offset"] is None:
        self.elements.append(stop)
        return

    # Add before the first bigger offset
    for (i, elem) in enumerate(self.elements):
        if elem["offset"] is None:
            continue
        if elem["offset"] > stop["offset"]:
            self.elements.insert(i, stop)
            return

    # If no bigger found, add at the end
    self.elements.append(stop)

_AbstractGradient.add = monkey_patch_gradient_add