def __init__(self, width, height, outputName): self.width = width self.height = height self.outputName = outputName self.ps = cairo.PDFSurface(self.outputName, self.width, self.height) self.cr = cairo.Context(self.ps) self.cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) self.cr.set_font_size(12) self.pgcr = pangocairo.CairoContext(self.cr) self.pgcr.set_antialias(cairo.ANTIALIAS_SUBPIXEL) self.layout = self.pgcr.create_layout() self.fontname = "Times New Roman" self.font = pango.FontDescription(self.fontname + " 8") self.layout.set_font_description(self.font) self.vOffset = 30 self.LOffset = 30 self.axesTop = 0.0 self.axesBot = 0.0 self.axesTick = 1.0 self.axesOriginNormalised = 0.0
def OnDrawItem(self, dc, rect, item, flags): if item == wx.NOT_FOUND: return default_font_size = get_default_font().GetPointSize() context = wx.lib.wxcairo.ContextFromDC(dc) context.rectangle(*rect) context.clip() pangocairo_context = pangocairo.CairoContext(context) pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pangocairo_context.create_layout() fontname = self.GetString(item) font = pango.FontDescription("{} {}".format(fontname, default_font_size)) layout.set_font_description(font) layout.set_text(fontname) color = tuple( [c / 255.0 for c in get_color(config["text_color"]).Get()]) context.set_source_rgb(*color) height = layout.get_pixel_extents()[1][3] y_adjust = int((rect.height - height) / 2.0) context.translate(rect.x + 3, rect.y + y_adjust) pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout)
def write_text(self, ctx, text, box_width=None, size=10, fill_color=(0.0, 0.0, 0.0), alignment=None): if HAS_PANGOCAIRO_MODULE: (attr, t, accel) = pango.parse_markup(text) pctx = pangocairo.CairoContext(ctx) l = pctx.create_layout() l.set_attributes(attr) fd = pango.FontDescription("%s %d" % (self.font_name, size)) l.set_font_description(fd) if box_width: l.set_width(int(box_width * pango.SCALE)) if alignment: l.set_alignment(alignment) pctx.update_layout(l) l.set_text(t) pctx.set_source_rgb(*fill_color) pctx.show_layout(l) return l.get_pixel_extents()[0] else: ctx.rel_move_to(0, size) ctx.select_font_face(self.font_name, cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) ctx.set_font_size(size) ctx.show_text(text) ctx.rel_move_to(0, size) return (0, 0, len(text) * size, size)
def __export_pdf_cb(self, event): maxx, maxy = self._main_area.get_max_area() true_width = int(maxx) true_height = int(maxy) # Create the new journal entry fileObject = datastore.create() act_meta = self.metadata fileObject.metadata['title'] = act_meta['title'] + ' (PDF)' fileObject.metadata['title_set_by_user'] = \ act_meta['title_set_by_user'] fileObject.metadata['mime_type'] = 'application/pdf' # TODO: add text thoughts into fulltext metadata # fileObject.metadata['fulltext'] = ... fileObject.metadata['icon-color'] = act_meta['icon-color'] fileObject.file_path = os.path.join(self.get_activity_root(), 'instance', '%i' % time.time()) filename = fileObject.file_path surface = cairo.PDFSurface(filename, true_width, true_height) cairo_context = cairo.Context(surface) context = pangocairo.CairoContext(cairo_context) self._main_area.export(context, true_width, true_height, False) surface.finish() datastore.write(fileObject, transfer_ownership=True) fileObject.destroy() del fileObject
def OnPaint(self, event): """Redraw the graph.""" dc = wx.PaintDC(self) #print dc ctx = wxcairo.ContextFromDC(dc) ctx = pangocairo.CairoContext(ctx) #print "DRAW" # Get widget size width, height = self.GetSize() #width,height = self.dc.GetSizeTuple() ctx.rectangle(0, 0, width, height) ctx.clip() ctx.set_source_rgba(1.0, 1.0, 1.0, 1.0) ctx.paint() ctx.save() ctx.translate(0.5 * width, 0.5 * height) ctx.scale(self.zoom_ratio, self.zoom_ratio) ctx.translate(-self.x, -self.y) self.graph.draw(ctx, highlight_items=self.highlight) ctx.restore() self.drag_action.draw(ctx)
def export_png(self, filename, size=None): """ Saves the contents of the widget to png file. The size of the image will be the size of the widget. @type filename: string @param filename: The path to the file where you want the chart to be saved. @type size: tuple @param size: Optional parameter to give the desired height and width of the image. """ if size is None: rect = self.get_allocation() width = rect.width height = rect.height else: width, height = size old_alloc = self.get_allocation self.get_allocation = lambda: gtk.gdk.Rectangle( 0, 0, width, height) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context(surface) context = pangocairo.CairoContext(ctx) self.set_size_request(width, height) self.draw(context) surface.write_to_png(filename) if size is not None: self.get_allocation = old_alloc
def draw(self): ctx = self.context # Fill the image with white solid color. ctx.rectangle(0, 0, self.width, self.height) ctx.set_source_rgb(1, 1, 1) ctx.fill_preserve() ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(1) ctx.stroke() # Translates context so that desired text upperleft corner is at 0,0 ctx.move_to(self.width // 10, self.height // 3) scale_factor = min(self.width, self.height) / 150.0 ctx.scale(scale_factor, scale_factor) pangocairo_context = pangocairo.CairoContext(ctx) pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pangocairo_context.create_layout() fontname = "Sans" font = pango.FontDescription(fontname + " 10") layout.set_font_description(font) layout.set_text(self.text) lg = cairo.LinearGradient(0, 0, self.width / scale_factor, 0) r, g, b = self.color lg.add_color_stop_rgba( 0.0, r, g, b, 0.0) lg.add_color_stop_rgba(0.05, r, g, b, 1.0) lg.add_color_stop_rgba(0.95, r, g, b, 1.0) lg.add_color_stop_rgba( 1.0, r, g, b, 0.0) ctx.set_source(lg) pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout)
def _draw_box(spec, text, c): # Text layout pc = pangocairo.CairoContext(c) text_layout, scale_ratio, text_width = _layout_text( pc, text, spec.height - 2 * TEXT_PADDING) # Global transform c.save() c.translate(spec.x, spec.y) c.rotate(spec.angle * math.pi / 180.) # Background if spec.width: width = spec.width else: width = text_width + 2 * TEXT_PADDING + RUNOUT c.set_source_rgb(*_parse_color(spec.bg_color)) c.rectangle(0, 0, width, spec.height) c.fill() # Foreground c.translate(TEXT_PADDING, TEXT_PADDING) c.scale(scale_ratio, scale_ratio) c.set_source_rgb(*_parse_color(spec.fg_color)) pc.show_layout(text_layout) c.restore()
def _render_text(self, surface): """Add legion height to a Cairo surface.""" if not self.show_height: return ctx = cairo.Context(surface) ctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) pctx = pangocairo.CairoContext(ctx) layout = pctx.create_layout() # TODO Vary font size with scale desc = pango.FontDescription("Monospace 17") layout.set_font_description(desc) layout.set_alignment(pango.ALIGN_CENTER) size = surface.get_width() layout.set_text(str(self.height)) width, height = layout.get_pixel_size() x = 0.65 * size y = 0.55 * size pctx.set_source_rgb(1, 1, 1) pctx.rectangle(x, y + 0.15 * height, 0.9 * width, 0.7 * height) pctx.fill() pctx.set_source_rgb(0, 0, 0) pctx.move_to(x, y) pctx.show_layout(layout)
def _render_hits(self, surface): """Add the number of hits to a Cairo surface""" if not self.creature or not self.creature.hits: return ctx = cairo.Context(surface) ctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) pctx = pangocairo.CairoContext(ctx) layout = pctx.create_layout() layout.set_alignment(pango.ALIGN_CENTER) # TODO Vary font size with scale desc = pango.FontDescription("monospace 20") layout.set_font_description(desc) layout.set_text(str(self.creature.hits)) size = surface.get_width() layout.set_width(size) pctx.set_source_rgb(1, 0, 0) x = 0.5 * size y = 0.2 * size pctx.set_source_rgb(1, 1, 1) pctx.set_line_width(1) width, height = layout.get_pixel_size() pctx.rectangle(x - 0.5 * width, y, 0.9 * width, 0.8 * height) pctx.fill() pctx.set_source_rgb(1, 0, 0) pctx.move_to(x, y) pctx.show_layout(layout)
def doPaint( self, text, antialias=True, color=( 255, 255, 255), background=None): """Render the __font onto a new Surface and return it. We ignore 'antialias' and use system settings. text -- (unicode) string with the text to doPaint antialias -- attempt to antialias the text or not color -- three or four-tuple of 0-255 values specifying rendering colour for the text background -- three or four-tuple of 0-255 values specifying rendering colour for the background, or None for trasparent background returns a pygame image instance """ log.info( 'doPaint: %r, antialias = %s, color=%s, background=%s', text, antialias, color, background) layout = self._createLayout(text) # determine pixel __size (logical, ink) = layout.get_pixel_extents() ink = pygame.rect.Rect(ink) # Create a new Cairo ImageSurface csrf, cctx = _cairoimage.newContext(ink.w, ink.h) cctx = pangocairo.CairoContext(cctx) # Mangle the colors on little-endian machines. The reason for this # is that Cairo writes native-endian 32-bit ARGB values whereas # Pygame expects endian-independent values in whatever format. So we # tell our users not to expect transparency here (avoiding the A issue) # and we swizzle all the colors around. # doPaint onto it if background is not None: background = _cairoimage.mangle_color(background) cctx.set_source_rgba(*background) cctx.paint() log.debug('incoming color: %s', color) color = _cairoimage.mangle_color(color) log.debug(' translated color: %s', color) cctx.new_path() cctx.layout_path(layout) cctx.set_source_rgba(*color) cctx.fill() # Create and return a new Pygame Image derived from the Cairo Surface return _cairoimage.asImage(csrf)
def getImage(idx): image = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(size_x), int(size_y)) context = cairo.Context(image) pangocairo_context = pangocairo.CairoContext(context) pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pangocairo_context.create_layout() layout.set_font_description(font) context.save() yoffset = 0 if space_h != None: dy = space_h offset = 0 i = 0 for text in listOfText: # ((10, yoffset), text, font) layout.set_text(text[0: max(idx - offset, 0)]) size = sizes[i] context.set_source_rgb(color[0], color[1], color[2]) context.translate((size_x - size) / 2, yoffset) pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout) context.restore() context.save() offset += len(text) yoffset += dy i+=1 return image
def draw_text_adjusted(ctx, text, x, y, width, height, max_char_number=None, text_color=(0, 0, 0, 1), align=pango.ALIGN_CENTER, width_adjust=0.7, height_adjust=0.8): """ Draw a text adjusted to a maximum character number Args: ctx (cairo.Context): The cairo context to use to draw. text (str): the text to draw. x/y (numbers): The position on the canvas. width/height (numbers): The area we want to write into (cairo units). max_char_number (number): If set a maximum character number. """ pc = pangocairo.CairoContext(ctx) layout = pc.create_layout() layout.set_width(int(width_adjust * width * pango.SCALE)) layout.set_alignment(align) fd = pango.FontDescription("Georgia Bold") fd.set_size(pango.SCALE) layout.set_font_description(fd) if max_char_number: # adjust size with the max character number layout.set_text('0' * max_char_number) adjust_font_size(layout, fd, width_adjust * width, height_adjust * height) # set the real text layout.set_text(text) if not max_char_number: adjust_font_size(layout, fd, width_adjust * width, height_adjust * height) # draw text_x, text_y, text_w, text_h = layout.get_extents()[1] ctx.save() ctx.set_source_rgba(*text_color) if align == pango.ALIGN_CENTER: x = x - (text_w / 2.0) / pango.SCALE - int(float(text_x) / pango.SCALE) y = y - (text_h / 2.0) / pango.SCALE - int(float(text_y) / pango.SCALE) else: y = y - (text_h / 2.0) / pango.SCALE - text_y / pango.SCALE ctx.translate(x, y) if align == pango.ALIGN_LEFT: # Hack to workaround what appears to be a Cairo bug: without # drawing a rectangle here, the translation above is not taken # into account for rendering the text. ctx.rectangle(0, 0, 0, 0) pc.show_layout(layout) ctx.restore()
def draw_speech_bubble(context, layout, x, y, w, h): """ Draw a speech bubble at a position Arguments: :param context: a cairo context :param layout: a pango layout :param x: x position of the bubble :param y: y position of the bubble :param w: width of the bubble :param h: height of the bubble """ layout.set_width((w - 10) * 1024) layout.set_ellipsize(pango.ELLIPSIZE_MIDDLE) textw, texth = layout.get_pixel_size() context.new_path() context.move_to(x + 0.45 * w, y + h * 0.1 + 2) context.line_to(x + 0.5 * w, y) context.line_to(x + 0.55 * w, y + h * 0.1 + 2) h = max(texth + 5, h) draw_rounded_rectangle(context, x, y + h * 0.1, w, h, r=5) context.close_path() context.set_line_width(2) context.set_source_rgb(168 / 255.0, 165 / 255.0, 134 / 255.0) context.stroke_preserve() context.set_source_rgb(253 / 255.0, 248 / 255.0, 202 / 255.0) context.fill() pcontext = pangocairo.CairoContext(context) pcontext.set_source_rgb(0, 0, 0) pcontext.move_to(x + 5, y + 5) pcontext.show_layout(layout)
def pango_families(): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1) cr = cairo.Context(surface) pcr = pangocairo.CairoContext(cr) layout = pcr.create_layout() pcx = layout.get_context() return [f.get_name() for f in pcx.list_families()]
def do_render(self, window, widget, background_area, cell_area, expose_area, flags): cairo_context = pangocairo.CairoContext(window.cairo_create()) layout = self.get_layout(widget) customAttr = self.get_property("custom") def set_attr(layout): attr = pango.AttrList() size = pango.AttrSize(int(11.5 * pango.SCALE), 0, -1) attr.insert(size) if customAttr and customAttr.attributes_dict: attributes_dict = customAttr.attributes_dict if attributes_dict.has_key("regex_include_match"): start, end = attributes_dict["regex_include_match"] pango_color = pango.AttrBackground(self.include_color.red, self.include_color.green, self.include_color.blue, start, end) attr.insert(pango_color) if attributes_dict.has_key("regex_exclude_match"): start, end = attributes_dict["regex_exclude_match"] pango_color = pango.AttrForeground(self.exclude_color.red, self.exclude_color.green, self.exclude_color.blue, start, end) attr.insert(pango_color) layout.set_attributes(attr) text = self.get_text() layout.set_text(text) set_attr(layout) # Vertically align the text cell_area.y += 2 cell_area.x += 1 cairo_context.move_to(cell_area.x, cell_area.y) cairo_context.show_layout(layout)
def draw_entry_text(self, cr, rect): ''' draw text.expose-event callback''' x, y, w, h = rect.x, rect.y, rect.width, rect.height with cairo_state(cr): # Clip text area first. draw_x = x + self.padding_x draw_y = y + self.padding_y draw_width = w - self.padding_x * 2 draw_height = h - self.padding_y * 2 cr.rectangle(draw_x, draw_y, draw_width, draw_height) cr.clip() # Create pangocairo context. context = pangocairo.CairoContext(cr) # Move text. cr.move_to(draw_x, draw_y) # Draw text. cr.set_source_rgb( *color_hex_to_cairo(self.entry_buffer.text_color)) context.update_layout(self._layout) context.show_layout(self._layout) # draw selection if not self.buffer.get_has_selection(): return bounds = self.buffer.get_selection_bounds() self.draw_selection_lines(bounds[0], bounds[1], cr, x, y)
def get_content_size(text, text_size=DEFAULT_FONT_SIZE, text_font=DEFAULT_FONT, wrap_width=None): ''' Get text size, in pixel. @param text: String or markup string. @param text_size: Text size, in pixel. @param text_font: Text font. @param wrap_width: The width of wrap rule, default don't wrap. @return: Return text size as (text_width, text_height), return (0, 0) if occur error. ''' if text: surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0) # don't need give size cr = cairo.Context(surface) context = pangocairo.CairoContext(cr) layout = context.create_layout() layout.set_font_description( pango.FontDescription("%s %s" % (text_font, text_size))) layout.set_markup(text) if wrap_width == None: layout.set_single_paragraph_mode(True) else: layout.set_width(wrap_width * pango.SCALE) layout.set_single_paragraph_mode(False) layout.set_wrap(pango.WRAP_WORD) return layout.get_pixel_size() else: return (0, 0)
def draw_text(self, x, y, text, color, size=10, family="Sans", angle=0): ''' draw text at x, y ''' context = self.context context.save() # move to x, y context.translate(x, y) context.rotate(angle) # create pango context pangocairo_context = pangocairo.CairoContext(context) pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) # set font layout = pangocairo_context.create_layout() fontname = "%s %d" % (family, size) font = pango.FontDescription(fontname) layout.set_font_description(font) # set color context.set_source_rgba(*color) # drow text layout.set_text(text) pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout) context.restore()
def save_cairo(evt): d = gtk.FileChooserDialog("Save file as svg, png or pdf", None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT)) if (d.run() == gtk.RESPONSE_ACCEPT): filename = d.get_filename() cr_s = None left, top, width, height = current_toys[0].get_save_size() if filename[-4:] == ".pdf": cr_s = cairo.PDFSurface(filename, width, height) elif filename[-4:] == ".png": cr_s = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) else: cr_s = cairo.SVGSurface(filename, width, height) cr = cairo.Context(cr_s) cr = pangocairo.CairoContext(cairo.Context(cr_s)) cr.translate(-left, -top) current_toys[0].draw(cr, (width, height), True) cr.show_page() del cr del cr_s d.destroy()
def draw_text(surf, position, quote, channel, font_colour, filename): context = cairo.Context(surf) textPosition = find_text_position(position) context.translate(textPosition[0],textPosition[1]) pangocairo_context = pangocairo.CairoContext(context) pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pangocairo_context.create_layout() layout.set_width(700 * pango.SCALE) layout.set_wrap(pango.WRAP_WORD) fontname = "Rekha" font = pango.FontDescription(fontname + "bold 38") layout.set_font_description(font) layout.set_text(u"""{}""".format(quote)) context.set_source_rgb(font_colour[0], font_colour[1], font_colour[2]) pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout) num_lines = layout.get_line_count() # filename = '/duta/images/modiout{}.png'.format(file_number) key = 'independence_test' #count = int(db.get(key)) count = randint(0,1000) filename = '{}_{}'.format(count, filename) #db.set(key, str(count + 1)) with open(filename, "wb") as image_file: surf.write_to_png(image_file)
def _addCanvasText2(self, text, pos, font, color=(0, 0, 0), **kwargs): if font.weight == 'bold': weight = cairo.FONT_WEIGHT_BOLD else: weight = cairo.FONT_WEIGHT_NORMAL self.ctx.select_font_face(font.face, cairo.FONT_SLANT_NORMAL, weight) orientation = kwargs.get('orientation', 'E') cctx = pangocairo.CairoContext(self.ctx) lout = cctx.create_layout() lout.set_alignment(pango.ALIGN_LEFT) lout.set_markup(text) fnt = pango.FontDescription('%s %d' % (font.face, font.size)) lout.set_font_description(fnt) iext, lext = lout.get_pixel_extents() w = lext[2] - lext[0] h = lext[3] - lext[1] #bw,bh=w*1.8,h*1.4 if orientation == 'W': dPos = pos[0] - w, pos[1] - h / 2. elif orientation == 'E': dPos = pos[0] - w / 2, pos[1] - h / 2. else: dPos = pos[0] - w / 2, pos[1] - h / 2. bgColor = kwargs.get('bgColor', (1, 1, 1)) self.ctx.set_source_rgb(*bgColor) self.ctx.rectangle(dPos[0], dPos[1], w, h) self.ctx.fill() self.ctx.move_to(dPos[0], dPos[1]) self.ctx.set_source_rgb(*color) cctx.update_layout(lout) cctx.show_layout(lout)
def _draw_text(cr, label, x, y, size, width, scale, heading, rgb, wrap=False): import textwrap final_scale = int(size * scale) * pango.SCALE label = str(label) if wrap: label = '\n'.join(textwrap.wrap(label, int(width / scale))) cc = pangocairo.CairoContext(cr) pl = cc.create_layout() fd = pango.FontDescription('Sans') fd.set_size(final_scale) pl.set_font_description(fd) if isinstance(label, (str, unicode)): pl.set_text(label.replace('\0', ' ')) elif isinstance(label, (float, int)): pl.set_text(str(label)) else: pl.set_text(str(label)) pl.set_width(int(width) * pango.SCALE) cc.save() cc.translate(x, y) cc.rotate(heading * DEGTOR) cr.set_source_rgb(rgb[0] / 255., rgb[1] / 255., rgb[2] / 255.) cc.update_layout(pl) cc.show_layout(pl) cc.restore()
def render_string_to_image(string, height): surf = cairo.ImageSurface(cairo.FORMAT_RGB24, height * 4 * len(string), height) context = cairo.Context(surf) # Do some font metrics wizardry pangocairo_context = pangocairo.CairoContext(context) layout = pangocairo_context.create_layout() font = pango.FontDescription("Sans") font.set_absolute_size(height * pango.SCALE) layout.set_font_description(font) layout.set_text(string) exts = layout.get_pixel_extents() width = exts[1][2] + -exts[0][0] # Draw a background rectangle: context.rectangle(0, 0, width, height) context.set_source_rgb(1, 1, 1) context.fill() # Draw the text context.translate(-exts[0][0], -exts[0][1]) context.set_source_rgb(0, 0, 0) pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout) # Crop the rendered image cropped = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height) cropped_context = cairo.Context(cropped) cropped_context.rectangle(0, 0, width, height) cropped_context.set_source_surface(surf, 0, 0) cropped_context.fill() return cropped
def _generate_image(self, num): w = 55 h = w pixmap = gdk.Pixmap(self.get_window(), w, h, -1) ctx = pixmap.cairo_create() ctx.rectangle(0, 0, w, h) ctx.set_source_rgb(0, 0, 0) ctx.fill() x = 0 y = 4 ctx.translate(x, y) circle_path = os.path.join(constants.GFX_PATH, 'media-circle.png') surface = cairo.ImageSurface.create_from_png(circle_path) ctx.set_source_surface(surface, 0, 0) ctx.paint() ctx.translate(-x, -y) ctx.set_source_rgb(255, 255, 255) pctx = pangocairo.CairoContext(ctx) play = pctx.create_layout() font = pango.FontDescription("sans 30") play.set_font_description(font) play.set_text(str(num)) dim = play.get_pixel_extents() ctx.translate(-dim[0][0], -dim[0][1]) xoff = (w - dim[0][2]) / 2 yoff = (h - dim[0][3]) / 2 ctx.translate(xoff, yoff) ctx.translate(-3, 0) pctx.show_layout(play) return pixmap
def write_image(self, filename): w = 8 + len(self.ref)*7 h = conf.SYMBOLS_IMAGE_SIZE[1] # create an image where the text fits img = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context(img) # background fill ctx.rectangle(0, 0, w, h) ctx.set_source_rgb(*conf.SYMBOLS_SWISS_BGCOLOR) ctx.fill_preserve() # border ctx.set_line_width(conf.SYMBOLS_IMAGE_BORDERWIDTH) levcol = conf.SYMBOLS_LEVELCOLORS[self.level] ctx.set_source_rgb(*levcol) ctx.stroke() # text ctx.set_source_rgb(*conf.SYMBOLS_TEXT_COLOR) pctx = pangocairo.CairoContext(ctx) pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pctx.create_layout() layout.set_font_description(self.txtfont) layout.set_text(self.ref) tw, th = layout.get_pixel_size() pctx.update_layout(layout) ctx.move_to(w-tw-conf.SYMBOLS_IMAGE_BORDERWIDTH/2, h-layout.get_iter().get_baseline()/pango.SCALE-conf.SYMBOLS_IMAGE_BORDERWIDTH/2) pctx.show_layout(layout) img.write_to_png(filename)
def get_text_size(text, font_name, font_height, layout_width, alignment=pango.ALIGN_LEFT, wrap_word=True): """ Returns width and height of the text in pixels """ surf = cairo.ImageSurface(cairo.FORMAT_A8, 1, 1) context = cairo.Context(surf) pangocairo_context = pangocairo.CairoContext(context) layout = pangocairo_context.create_layout() layout.set_width(layout_width * pango.SCALE) font = pango.FontDescription(font_name) font.set_absolute_size(font_height * pango.SCALE) layout.set_font_description(font) layout.set_alignment(alignment) if wrap_word: layout.set_wrap(pango.WRAP_WORD) layout.set_text(text) context.set_source_rgb(1, 0, 1.0) pangocairo_context.update_layout(layout) pangocairo_context.show_layout(layout) return layout.get_pixel_size()
def write_image(self, filename): # get text size self.txtctx_layout.set_text(self.ref) tw, th = self.txtctx_layout.get_pixel_size() # create an image where the text fits w = conf.SYMBOLS_IMAGE_SIZE[0] h = conf.SYMBOLS_IMAGE_SIZE[1] img = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) ctx = cairo.Context(img) # background fill ctx.arc(w/2, h/2, w/2, 0, 2*pi) if self.difficulty > 6: color = conf.SYMBOLS_FREERIDE_COLOR else: color = conf.SYMBOLS_SKI_COLORS[self.difficulty] ctx.set_source_rgb(*color) ctx.fill() # reference text ctx.set_source_rgb(*conf.SYMBOLS_TEXT_COLOR) pctx = pangocairo.CairoContext(ctx) pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pctx.create_layout() layout.set_font_description(self.txtfont) layout.set_text(self.ref) pctx.update_layout(layout) ctx.move_to((w-tw)/2, (h-layout.get_iter().get_baseline()/pango.SCALE)/2.0) pctx.show_layout(layout) img.write_to_png(filename)
def use_pango_font(font, start, count, will_call_prepost=False): import pango, cairo, pangocairo fontDesc = pango.FontDescription(font) a = array.array('b', itertools.repeat(0, 256 * 256)) surface = cairo.ImageSurface.create_for_data(a, cairo.FORMAT_A8, 256, 256) context = pangocairo.CairoContext(cairo.Context(surface)) layout = context.create_layout() fontmap = pangocairo.cairo_font_map_get_default() font = fontmap.load_font(fontmap.create_context(), fontDesc) layout.set_font_description(fontDesc) metrics = font.get_metrics() descent = metrics.get_descent() d = pango.PIXELS(descent) linespace = metrics.get_ascent() + metrics.get_descent() width = metrics.get_approximate_char_width() glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT) glPixelStorei(GL_UNPACK_SWAP_BYTES, 0) glPixelStorei(GL_UNPACK_LSB_FIRST, 1) glPixelStorei(GL_UNPACK_ROW_LENGTH, 256) glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 256) glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0) glPixelStorei(GL_UNPACK_SKIP_ROWS, 0) glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glPixelZoom(1, -1) base = glGenLists(count) for i in range(count): ch = unichr(start + i) layout.set_text(ch) w, h = layout.get_size() context.save() context.new_path() context.rectangle(0, 0, 256, 256) context.set_source_rgba(0., 0., 0., 0.) context.set_operator(cairo.OPERATOR_SOURCE) context.paint() context.restore() context.save() context.set_source_rgba(1., 1., 1., 1.) context.set_operator(cairo.OPERATOR_SOURCE) context.move_to(0, 0) context.update_layout(layout) context.show_layout(layout) context.restore() w, h = pango.PIXELS(w), pango.PIXELS(h) glNewList(base + i, GL_COMPILE) glBitmap(0, 0, 0, 0, 0, h - d, '') if not will_call_prepost: pango_font_pre() if w and h: glDrawPixels(w, h, GL_LUMINANCE, GL_UNSIGNED_BYTE, a) glBitmap(0, 0, 0, 0, w, -h + d, '') if not will_call_prepost: pango_font_post() glEndList() glPopClientAttrib() return base, pango.PIXELS(width), pango.PIXELS(linespace)
def _draw_font(cr, x, y, font_name, text, align, wrap_width, rot_angle): cr.save() pc = pangocairo.CairoContext(cr) pc.set_antialias(cairo.ANTIALIAS_SUBPIXEL) layout = pc.create_layout() layout.set_font_description(pango.FontDescription(font_name)) layout.set_text(text) if wrap_width: layout.set_wrap(pango.WRAP_WORD) layout.set_width(pango.SCALE * wrap_width) dim = layout.get_pixel_size() cr.translate(x, y) x = 0 y = 0 if align == 'right': x = -dim[0] if align == 'center': x = -dim[0] / 2 y = -dim[1] / 2 cr.rotate(rot_angle) cr.translate(x, y) pc.update_layout(layout) pc.show_layout(layout) cr.restore() return dim