def set_ctx_color(ctx, color): if isinstance(color, tuple): ctx.set_source_rgba(*color) elif isinstance(color, Color): ctx.set_source_rgba(*color.get_array()) elif isinstance(color, str): ctx.set_source_rgba(*Color.from_html(color).get_array()) else: ctx.set_source(color)
def draw_fill(ctx, color=Color(1, 1, 1,1)): ctx.save() if isinstance(color, Color): ctx.set_source_rgba(*color.get_array()) elif isinstance(color, str): ctx.set_source_rgba(*Color.from_html(color).get_array()) elif isinstance(color, cairo.Pattern): ctx.set_source(color) ctx.fill() ctx.restore()
def draw_stroke(ctx, line_width, color=Color(0,0,0,1)): ctx.save() if isinstance(color, Color): ctx.set_source_rgba(*color.get_array()) elif isinstance(color, str): ctx.set_source_rgba(*Color.from_html(color).get_array()) else: ctx.set_source(color) ctx.set_line_width(line_width) ctx.stroke() ctx.restore()
def draw_text(ctx, text, x, y, width=None, corner=5, align=None, fit_width=False, height=None, fit_height=False, text_color=None, back_color=None, border_color=None, border_width=1, padding=0, font_name=None, pre_draw=None): layout = PangoCairo.create_layout(ctx) font = Pango.FontDescription.from_string(font_name) layout.set_wrap(Pango.WrapMode(0)) layout.set_font_description(font) layout.set_alignment(Pango.Alignment(0)) layout.set_markup(text) text_rect = layout.get_pixel_extents()[1] l = text_rect.x t = text_rect.y w= text_rect.width h = text_rect.height scale_x = 1 scale_y = 1 if width: if width<w: if fit_width: scale_x = width/float(w) else: layout.set_width(int(width*Pango.SCALE)) #w = width else: width = w if height: if height<h: if fit_height: scale_y = height/float(h) else: h = height else: height = 0 if align: if align.find("bottom-center")>=0: y -= t+h*scale_y+2*padding elif align.find("bottom")>=0: y -= -t+h*scale_y+padding if align.find("right")>=0: x -= w*scale_x+padding elif align.find("hcenter")>=0: x -= (w*scale_x+padding)*.5 if back_color: ctx.save() if pre_draw: pre_draw(ctx) ctx.translate(x, y) ctx.scale(scale_x, scale_y) draw_rounded_rectangle(ctx, 0, 0, w+2*padding, h+2*padding, corner) ctx.restore() draw_fill(ctx, back_color) if border_color: ctx.save() if pre_draw: pre_draw(ctx) ctx.translate(x, y) ctx.scale(scale_x, scale_y) draw_rounded_rectangle(ctx, 0, 0, w+2*padding, h+2*padding, corner) ctx.restore() draw_stroke(ctx, border_width, border_color) if not text_color: ctx.set_source_rgba(0,0,0,1) elif isinstance(text_color, Color): ctx.set_source_rgba(*text_color.get_array()) elif type(text_color) is str: ctx.set_source_rgba(*Color.from_html(text_color).get_array()) ctx.save() if pre_draw: pre_draw(ctx) ctx.translate(x, y) ctx.move_to(padding, padding) ctx.scale(scale_x, scale_y) PangoCairo.show_layout(ctx, layout) ctx.restore() return Rect(x, y, w+2*padding, h+2*padding)