def set_source_rgb(self, colour: Union[ColorType, List[ColorType]], ctx: cairocffi.Context = None): # If an alternate context is not provided then we draw to the # drawer's default context if ctx is None: ctx = self.ctx if isinstance(colour, list): if len(colour) == 0: # defaults to black ctx.set_source_rgba(*utils.rgb("#000000")) elif len(colour) == 1: ctx.set_source_rgba(*utils.rgb(colour[0])) else: linear = cairocffi.LinearGradient(0.0, 0.0, 0.0, self.height) step_size = 1.0 / (len(colour) - 1) step = 0.0 for c in colour: rgb_col = utils.rgb(c) if len(rgb_col) < 4: rgb_col[3] = 1 linear.add_color_stop_rgba(step, *rgb_col) step += step_size ctx.set_source(linear) else: ctx.set_source_rgba(*utils.rgb(colour))
def coloured_bezier(ctx: cairo.Context, p0, p1, p2, p3, colors, width, detail=100, fade=None): p0 = np.array(p0) p1 = np.array(p1) p2 = np.array(p2) p3 = np.array(p3) bez, bezd = cubic_bezier(p0, p1, p2, p3, numpoints=detail) bezd = normalize(bezd, norm='l2', axis=1) frac_sum = -.5 for color, frac in colors: (r, g, b, a) = color if fade is None: ctx.set_source_rgba(r, g, b, a) else: ctx.set_source(fade_pattern(p0[0], p0[1], p3[0], p3[1], r, g, b, a, fade)) ctx.set_line_width(frac*width) frac_sum += frac/2 ctx.move_to(bez[0][0] - width * frac_sum * bezd[0][1], bez[0][1] + width * frac_sum * bezd[0][0]) for i in range(0, bez.shape[0] - 3, 3): ctx.curve_to(bez[i + 1][0] - width * frac_sum * bezd[i + 1][1], bez[i + 1][1] + width * frac_sum * bezd[i + 1][0], bez[i + 2][0] - width * frac_sum * bezd[i + 2][1], bez[i + 2][1] + width * frac_sum * bezd[i + 2][0], bez[i + 3][0] - width * frac_sum * bezd[i + 3][1], bez[i + 3][1] + width * frac_sum * bezd[i + 3][0]) # for i in range(0, bez.shape[0] - 3, 2): # ctx.move_to(bez[i][0] - width * frac_sum * bezd[i][1], bez[i][1] + width * frac_sum * bezd[i][0]) # ctx.curve_to(bez[i + 1][0] - width * frac_sum * bezd[i + 1][1], bez[i + 1][1] + width * frac_sum * bezd[i + 1][0], # bez[i + 2][0] - width * frac_sum * bezd[i + 2][1], bez[i + 2][1] + width * frac_sum * bezd[i + 2][0], # bez[i + 3][0] - width * frac_sum * bezd[i + 3][1], bez[i + 3][1] + width * frac_sum * bezd[i + 3][0]) ctx.stroke() frac_sum += frac/2