Python pangocairo.CairoContext() Examples

The following are 10 code examples of pangocairo.CairoContext(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pangocairo , or try the search function .
Example #1
Source File: chart.py    From openxenmanager with GNU General Public License v2.0 6 votes vote down vote up
def export_svg(self, filename, size=None):
        """
        Saves the contents of the widget to svg 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.SVGSurface(filename, width, height)
        ctx = cairo.Context(surface)
        context = pangocairo.CairoContext(ctx)
        self.draw(context)
        surface.finish()
        if size is not None:
            self.get_allocation = old_alloc 
Example #2
Source File: cairo_backend.py    From symbolator with MIT License 5 votes vote down vote up
def draw_text(x, y, text, font, text_color, spacing, c):
    c.save()
    c.set_source_rgba(*rgb_to_cairo(text_color))
    font = cairo_font(font)

    c.translate(x, y)
    
    if use_pygobject:
      status, attrs, plain_text, _ = pango.parse_markup(text, len(text), '\0')
      
      layout = pangocairo.create_layout(c)
      pctx = layout.get_context()
      fo = cairo.FontOptions()
      fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
      pangocairo.context_set_font_options(pctx, fo)
      layout.set_font_description(font)
      layout.set_spacing(spacing * pango.SCALE)
      layout.set_text(plain_text, len(plain_text))
      layout.set_attributes(attrs)
      pangocairo.update_layout(c, layout)
      pangocairo.show_layout(c, layout)

    else: # pyGtk
      attrs, plain_text, _ = pango.parse_markup(text)
      
      pctx = pangocairo.CairoContext(c)
      pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
      layout = pctx.create_layout()
      layout.set_font_description(font)
      layout.set_spacing(spacing * pango.SCALE)
      layout.set_text(plain_text)
      layout.set_attributes(attrs)
      pctx.update_layout(layout)
      pctx.show_layout(layout)
      
    c.restore() 
Example #3
Source File: syntrax.py    From syntrax with MIT License 5 votes vote down vote up
def cairo_text_bbox(text, font_params, scale=1.0):
  surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
  ctx = cairo.Context(surf)

  # The scaling must match the final context.
  # If not there can be a mismatch between the computed extents here
  # and those generated for the final render.
  ctx.scale(scale, scale)

  font = cairo_font(font_params)

  if use_pygobject:
    layout = pangocairo.create_layout(ctx)
    pctx = layout.get_context()
    fo = cairo.FontOptions()
    fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
    pangocairo.context_set_font_options(pctx, fo)
    layout.set_font_description(font)
    layout.set_text(text, len(text))
    re = layout.get_pixel_extents()[1]
    extents = (re.x, re.y, re.x + re.width, re.y + re.height)

  else: # pyGtk
    pctx = pangocairo.CairoContext(ctx)
    pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
    layout = pctx.create_layout()
    layout.set_font_description(font)
    layout.set_text(text)

    #print('@@ EXTENTS:', layout.get_pixel_extents()[1])
    extents = layout.get_pixel_extents()[1]
  w = extents[2] - extents[0]
  h = extents[3] - extents[1]
  x0 = - w // 2.0
  y0 = - h // 2.0
  return [x0,y0, x0+w,y0+h] 
Example #4
Source File: syntrax.py    From syntrax with MIT License 5 votes vote down vote up
def cairo_draw_text(x, y, text, font, text_color, c):
  c.save()
  #print('## TEXT COLOR:', text_color)
  c.set_source_rgba(*rgb_to_cairo(text_color))
  font = cairo_font(font)

  c.translate(x, y)

  if use_pygobject:
    layout = pangocairo.create_layout(c)
    pctx = layout.get_context()
    fo = cairo.FontOptions()
    fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
    pangocairo.context_set_font_options(pctx, fo)
    layout.set_font_description(font)
    layout.set_text(text, len(text))
    pangocairo.update_layout(c, layout)
    pangocairo.show_layout(c, layout)

  else: # pyGtk
    pctx = pangocairo.CairoContext(c)
    pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
    layout = pctx.create_layout()
    layout.set_font_description(font)
    layout.set_text(text)
    pctx.update_layout(layout)
    pctx.show_layout(layout)

  c.restore() 
Example #5
Source File: punchcard.py    From Punchcard with MIT License 5 votes vote down vote up
def __init__(self, dc=None):
        self.dc = dc or cairo.Context(
            cairo.ImageSurface(cairo.FORMAT_RGB24, 1, 1))
        self.pc = pangocairo.CairoContext(self.dc)
        self.layout = self.pc.create_layout() 
Example #6
Source File: chart.py    From openxenmanager with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #7
Source File: indic_scribe_python2.py    From chamanti_ocr with Apache License 2.0 5 votes vote down vote up
def scribe(text, fontname, ten=10, style=0,
           sz=48, spc=1, movex=10, movey=0, twist=0):
    lines = text.split('\n')
    n_lines = len(lines)
    n_letters = max(len(line) for line in lines)

    size_x = 3 * ten * n_letters + 5 * ten
    size_y = 5 * ten * n_lines + 5 * ten

    # print("Lines: {} Letters:{} Size:{}x{}".format(
    #     n_lines, n_letters, size_x, size_y))

    data = np.zeros((size_y, size_x, 4), dtype=np.uint8)
    surf = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32,
                                              size_x, size_y)
    cr = cairo.Context(surf)
    pc = pangocairo.CairoContext(cr)
    pc.set_antialias(cairo.ANTIALIAS_SUBPIXEL)

    layout = pc.create_layout()
    layout.set_text(text)

    style = styles[style]
    font_style = "{} {} {}".format(fontname, style, (sz * ten)//10)
    layout.set_font_description(pango.FontDescription(font_style))
    layout.set_spacing(spc * 32)

    cr.rectangle(0, 0, size_x, size_y)
    cr.set_source_rgb(1, 1, 1)
    cr.fill()
    cr.translate(ten, 0)
    cr.set_source_rgb(0, 0, 0)

    pc.update_layout(layout)
    pc.show_layout(layout)

    return data[:, :, 0] < 128 
Example #8
Source File: cairo_backend.py    From symbolator with MIT License 4 votes vote down vote up
def cairo_text_bbox(text, font_params, spacing=0, scale=1.0):
    surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
    ctx = cairo.Context(surf)

    # The scaling must match the final context.
    # If not there can be a mismatch between the computed extents here
    # and those generated for the final render.
    ctx.scale(scale, scale)
    
    font = cairo_font(font_params)


    if use_pygobject:
      status, attrs, plain_text, _ = pango.parse_markup(text, len(text), '\0')
      
      layout = pangocairo.create_layout(ctx)
      pctx = layout.get_context()
      fo = cairo.FontOptions()
      fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
      pangocairo.context_set_font_options(pctx, fo)
      layout.set_font_description(font)
      layout.set_spacing(spacing * pango.SCALE)
      layout.set_text(plain_text, len(plain_text))
      layout.set_attributes(attrs)

      li = layout.get_iter() # Get first line of text
      baseline = li.get_baseline() / pango.SCALE

      re = layout.get_pixel_extents()[1] # Get logical extents
      extents = (re.x, re.y, re.x + re.width, re.y + re.height)

    else: # pyGtk
      attrs, plain_text, _ = pango.parse_markup(text)

      pctx = pangocairo.CairoContext(ctx)
      pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
      layout = pctx.create_layout()
      layout.set_font_description(font)
      layout.set_spacing(spacing * pango.SCALE)
      layout.set_text(plain_text)
      layout.set_attributes(attrs)

      li = layout.get_iter() # Get first line of text
      baseline = li.get_baseline() / pango.SCALE

      #print('@@ EXTENTS:', layout.get_pixel_extents()[1], spacing)
      extents = layout.get_pixel_extents()[1] # Get logical extents

    return [extents[0], extents[1], extents[2], extents[3], baseline] 
Example #9
Source File: line_draw.py    From namsel with MIT License 4 votes vote down vote up
def draw_line2(line, font, size):
#     size = "40"
    if line.strip().endswith(u'་'):
        line = line.strip(u'་')
        line = line + u'་'
    line = line.strip(u' ')
    w = 8000
    h = 250
    spacing = 'normal' # this doesn't seem to work anyway
#     for spacing in ['normal', 'condensed']:

    surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
    context = cairo.Context(surf)
    
    #draw a background rectangle:
    context.rectangle(0,0,w,h)
    context.set_source_rgb(1, 1, 1)
    context.fill()
    
    #get font families:
    
#         font_map = pangocairo.cairo_font_map_get_default()
#    context.translate(0,0)
    
    pangocairo_context = pangocairo.CairoContext(context)
    pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
    
    layout = pangocairo_context.create_layout()
    #fontname = sys.argv[1] if len(sys.argv) >= 2 else "Sans"
#         font = pango.FontDescription(fontname + " 200")
    font_params = [font,'normal', 'normal', spacing, str(size)]
    font = pango.FontDescription(" ".join(font_params))
#     font.set_stretch(pango.STRETCH_CONDENSED)
#             else:
#                 font = pango.FontDescription(fontname + " bold 200")
        
    layout.set_font_description(font)
    
    layout.set_text(line)
    context.set_source_rgb(0, 0, 0)
    pangocairo_context.update_layout(layout)
    pangocairo_context.show_layout(layout)
#             fname = "/tmp/%s%d.png" % (fontname, randint(0,20000000))
    fname = "/tmp/%s.png" % ('-'.join(font_params))
#         fname = outpath + fontname + '.png'
#         codecs.open(outpath + fontname + '.gt.txt', 'w', 'utf-8').write(line)
    with open(fname, "wb") as image_file:
            surf.write_to_png(image_file)
            
    im = Image.open(fname)
#         im = im.convert('L')
    im = im.convert('L')
    a = np.asarray(im, 'f')
    os.remove(fname)
    return a
#         a = trim(a)/255
#         a = add_padding(a, padding=2)
#         Image.fromarray(a*255).save(fname) 
Example #10
Source File: glnav3.py    From hazzy with GNU General Public License v2.0 4 votes vote down vote up
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)