Python cairo 模块,Context() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cairo.Context()

项目:pgn2anki    作者:asdfjkl    | 项目源码 | 文件源码
def open_svg_as_image(fn, width, height):
    for i in range(10):
        try:
            tmpfd, tmppath = tempfile.mkstemp(".png")
            tmpfile = os.fdopen(tmpfd,'w')

            file = StringIO.StringIO()
            svgsurface = cairo.SVGSurface (file, width, height)
            svgctx = cairo.Context(svgsurface)
            svg = rsvg.Handle(file=fn)
            svgwidth = svg.get_property('width')
            svgheight = svg.get_property('height')
            svgctx.scale(width/float(svgwidth),height/float(svgheight))
            svg.render_cairo(svgctx)

            svgsurface.write_to_png(tmpfile)
            svgsurface.finish()
            tmpfile.close()

            tmpfile = open(tmppath, 'r')
            imgsurface = cairo.ImageSurface.create_from_png(tmpfile)
            imgwidth = imgsurface.get_width()
            imgheight = imgsurface.get_height()

            data = imgsurface.get_data()

            im = Image.frombuffer("RGBA",(imgwidth, imgheight), data ,"raw","RGBA",0,1)
            os.remove(tmppath)
            break
        except MemoryError:
            print 'Memory Error. Try again ...'
            continue
    else:
        raise Exception('Problem loading image {0}'.format(fn))
    return im
项目:ns3-rdma    作者:bobzhuyb    | 项目源码 | 文件源码
def layout(self, width):
        self.__width = width
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)
        ctx = cairo.Context(surface)
        line_height = 0
        total_height = self.__padding
        line_used = self.__padding
        for legend in self.__legends:
            (t_width, t_height) = ctx.text_extents(legend)[2:4]
            item_width = self.__padding + self.__padding + t_width + self.__padding
            item_height = t_height + self.__padding
            if item_height > line_height:
                line_height = item_height
            if line_used + item_width > self.__width:
                line_used = self.__padding + item_width
                total_height += line_height
            else:
                line_used += item_width
            x = line_used - item_width
        total_height += line_height
        self.__height = total_height
项目:iutils    作者:inconvergent    | 项目源码 | 文件源码
def export_svg(fn, paths, size, line_with=0.1, scale_factor=None):

  from cairo import SVGSurface, Context
  from .ddd import spatial_sort_2d as sort

  if not scale_factor:
    scale_factor = size

  s = SVGSurface(fn, size, size)
  c = Context(s)

  c.set_line_width(0.1)

  paths = sort(paths)

  for path in paths:
    path *= scale_factor

    c.new_path()
    c.move_to(*path[0,:])
    for p in path[1:]:
      c.line_to(*p)
    c.stroke()

  c.save()
项目:gprime    作者:GenealogyCollective    | 项目源码 | 文件源码
def draw(self, cairo_context, pango_layout, width, dpi_x, dpi_y):
        """Draw itself onto a cairo surface.

        @param cairo_context: context to draw on
        @param type: cairo.Context class
        @param pango_layout: pango layout to write on
        @param type: Pango.Layout class
        @param width: width of available space for this element
        @param type: device points
        @param dpi_x: the horizontal resolution
        @param type: dots per inch
        @param dpi_y: the vertical resolution
        @param type: dots per inch

        @return: height of the element
        @rtype: device points

        """
        raise NotImplementedError
项目:svg-sorter    作者:inconvergent    | 项目源码 | 文件源码
def export_svg(fn, paths, w, h, line_width=0.1):

  from cairo import SVGSurface, Context

  s = SVGSurface(fn, w, h)
  c = Context(s)

  c.set_line_width(line_width)

  for path in paths:

    c.new_path()
    c.move_to(*path[0,:])
    for p in path[1:]:
      c.line_to(*p)
    c.stroke()

  c.save()
项目:stats    作者:fsr    | 项目源码 | 文件源码
def render(self):
        col_labels = ColLabels(self)
        row_labels = RowLabels(self)
        chart = Chart(self)
        title = Title(self)
        grid = sizers.GridSizer(3, 2, self.padding, self.padding)
        grid.add_spacer()
        grid.add(col_labels)
        grid.add(row_labels)
        grid.add(chart)
        grid.add_spacer()
        grid.add(title)
        sizer = sizers.VerticalSizer()
        sizer.add(grid, border=self.padding)
        sizer.fit()
        surface = cairo.ImageSurface(
            cairo.FORMAT_RGB24, int(sizer.width), int(sizer.height))
        dc = cairo.Context(surface)
        dc.set_source_rgb(1, 1, 1)
        dc.paint()
        col_labels.render(dc)
        row_labels.render(dc)
        chart.render(dc)
        title.render(dc)
        return surface
项目:TMDLang    作者:aguai    | 项目源码 | 文件源码
def barCoord(n):
    '''
    returns ((x-left-top, y-left-top),
            (x-left-buttom, y-right-buttom),
            (x-right-top, y-right-top),
            (x-right-buttom, y-right-buttom))
            coordinate of a bar area   
    '''
    return ((100 + (n % 6) * 380, 430 + (n // 6) * 331),                # left x-axis 100pt for margin blank    
            (100 + (n % 6) * 380, 430 + (n // 6) * 331 + 252),          # top  y-axis 430pt for title
            (100 + (n % 6) * 380 + 380, 430 + (n // 6) * 331),          # 252 is 1.5em for chord 1em * 3 for melody 56pt per em
            (100 + (n % 6) * 380 + 380, 430 + (n // 6) * 331 + 252))


# ctx = cairo.Context(cairo.PDFSurface("haha.pdf", 2480.0, 3508.0))
# ctx.set_font_size(30)
# ctx.select_font_face("FreeSerif", cairo.FONT_SLANT_NORMAL,
#                     cairo.FONT_WEIGHT_NORMAL)
项目:TMDLang    作者:aguai    | 项目源码 | 文件源码
def main():

    ps = cairo.PDFSurface("pdffile.pdf", 504, 648)
    cr = cairo.Context(ps)

    cr.set_source_rgb(0, 0, 0)
    cr.select_font_face("FreeSerif", cairo.FONT_SLANT_NORMAL,
                        cairo.FONT_WEIGHT_NORMAL)
    cr.set_font_size(40)
    cr.move_to(10, 50)
    cr.show_text(chr(119046) +'1 2 3 4 5' + chr(119047) )
    cr.set_line_width(11)
    cr.move_to(100, 100)
    cr.line_to(20, 300)

    cr.show_page()
项目:TikZ    作者:ellisk42    | 项目源码 | 文件源码
def draw(self,context = None, adjustCanvasSize = False):
        if adjustCanvasSize:
            x0,y0,x1,y1 = self.extent()
            self = self.translate(-x0 + 1,-y0 + 1)
            x0,y0,x1,y1 = self.extent()
            W = max([256, 16*(y1 + 1), 16*(x1 + 1)])
            H = W
        else:
            W = 256
            H = 256

        if context == None:
            data = np.zeros((W,H), dtype=np.uint8)
            surface = cairo.ImageSurface.create_for_data(data,cairo.FORMAT_A8,W,H)
            context = cairo.Context(surface)
        for l in self.lines: l.draw(context)
        data = np.flip(data, 0)/255.0
        if adjustCanvasSize:
            import scipy.ndimage
            return scipy.ndimage.zoom(data,W/256.0)
        return data
项目:godot-themes    作者:Geequlim    | 项目源码 | 文件源码
def svg2png(svg_file, output_file, scale=1):
    # Get the svg files content
    svg_data = open(svg_file).read()

    # Get the width / height inside of the SVG
    doc = minidom.parseString(svg_data)
    width = [path.getAttribute('width') for path in doc.getElementsByTagName('svg')][0]
    height = [path.getAttribute('height') for path in doc.getElementsByTagName('svg')][0]
    width = int(round(float(re.compile('(\d+\.*\d*)\w*').findall(width)[0])))
    height = int(round(float(re.compile('(\d+\.*\d*)\w*').findall(height)[0])))
    doc.unlink()

    # Create the png
    img = cairo.ImageSurface(
        cairo.FORMAT_ARGB32, width * scale, height * scale)
    ctx = cairo.Context(img)
    ctx.scale(scale, scale)
    handler = rsvg.Handle(None, str(svg_data))
    handler.render_cairo(ctx)
    img.write_to_png(output_file)
    print("{} ==> {}".format(svg_file, output_file))
项目:paperwork-backend    作者:openpaperwork    | 项目源码 | 文件源码
def __render_img(self, size, pdf_page=None):
        # TODO(Jflesch): In a perfect world, we shouldn't use ImageSurface.
        # we should draw directly on the GtkImage.window.cairo_create()
        # context. It would be much more efficient.

        logger.debug('Building img from pdf: {}'.format(size))

        if pdf_page is None:
            pdf_page = self.pdf_page

        base_size = self.get_base_size(pdf_page)

        width = int(size[0])
        height = int(size[1])
        factor_w = width / base_size[0]
        factor_h = height / base_size[1]

        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        ctx = cairo.Context(surface)
        ctx.scale(factor_w, factor_h)
        pdf_page.render(ctx)
        return surface2image(surface)
项目:paperwork-backend    作者:openpaperwork    | 项目源码 | 文件源码
def print_page_cb(self, print_op, print_context, keep_refs={}):
        pdf_page = self.pdf_page
        base_size = self.get_base_size(pdf_page)

        ctx = print_context.get_cairo_context()

        logger.debug("Context: %d x %d" % (print_context.get_width(),
                                           print_context.get_height()))
        logger.debug("Size: %d x %d" % (base_size[0], base_size[1]))

        factor_x = float(print_context.get_width()) / float(base_size[0])
        factor_y = float(print_context.get_height()) / float(base_size[1])
        factor = min(factor_x, factor_y)

        logger.debug("Scale: %f x %f --> %f" % (factor_x, factor_y, factor))

        ctx.scale(factor, factor)

        self.pdf_page.render_for_printing(ctx)
        return None
项目:pyphy-engine    作者:pulkitag    | 项目源码 | 文件源码
def generate_image(self, returnContext=False, 
                                cropObject=None, cropSz=None):
        '''
            returnContext: returns object of type cairo.Context
            cropObject   : the object around which image needs to be cropped
            cropSz       : the size of the image crop
        '''
        data    = np.zeros((self.ySz_, self.xSz_, 4), dtype=np.uint8)
        data[:] = self.baseCanvas_.im[:]
        surface = cairo.ImageSurface.create_for_data(data, 
                                cairo.FORMAT_ARGB32, self.xSz_, self.ySz_)
        cr      = cairo.Context(surface)
        for key, obj in self.objects_.iteritems():
            obj.imprint(cr, self.xSz_, self.ySz_)
        if returnContext:
            return data, cr
        else:
            return data
项目:gsTiles    作者:schmidtc    | 项目源码 | 文件源码
def getContext(surface, tx, ty, zoom):
    """
    getContext -- Preps a cairo context for a tile

    """
    ctx = cairo.Context(surface)
    ctx.set_antialias(cairo.ANTIALIAS_NONE)
    ctx.set_line_join(cairo.LINE_JOIN_BEVEL)

    numtiles = 2**zoom
    meters_per_tile = SPHEREMERC_GROUND_SIZE / numtiles

    #3rd
    ctx.translate(-WIDTH*tx, -HEIGHT*ty) #shift to tile coords
    #2nd
    ctx.scale(WIDTH / meters_per_tile, -HEIGHT / meters_per_tile) #scale to pixels
    #1st
    ctx.translate(SPHEREMERC_GROUND_SIZE/2.0, -SPHEREMERC_GROUND_SIZE/2.0) #shift origin.
    return ctx
项目:htmlDE    作者:freundTech    | 项目源码 | 文件源码
def _cairo_surface_extents(surface):
    if surface == None:
        return False
    cr = cairo.Context(surface)
    x1, y1, x2, y2 = cr.clip_extents()
    x1 = floor(x1)
    y1 = floor(y1)
    x2 = ceil(x2)
    y2 = ceil(y2)
    x2 -= x1
    y2 -= y1

    extents = cairo.RectangleInt()
    extents.x = x1
    extents.y = y1
    extents.width = x2
    extents.height = y2

    return extents
项目:zellij    作者:nedbat    | 项目源码 | 文件源码
def __init__(self, width=None, height=None, name=None, bounds=None, bg=(1, 1, 1), format=None):
        """Create a new Cairo drawing.

        If `bounds` is provided, it's a Bounds describing the extend of the
        drawing.  Otherwise, provide `width` and `height` to specify a size
        explicitly.

        `bg` is the background color to paint initially.

        """
        if bounds is None:
            assert width is not None
            assert height is not None
            bounds = Bounds(0, 0, width, height)
        self.bounds = bounds

        self.width = int(self.bounds.width)
        self.height = int(self.bounds.height)

        self.name, self.format = name_and_format(name, format)

        if self.format == 'png':
            self.surface = cairo.ImageSurface(cairo.Format.ARGB32, self.width, self.height)
        elif self.format == 'svg':
            self.surface = cairo.SVGSurface(self.name, self.width, self.height)
        self.ctx = cairo.Context(self.surface)
        self.ctx.set_antialias(cairo.Antialias.BEST)
        self.ctx.set_line_cap(cairo.LineCap.ROUND)
        self.ctx.set_line_join(cairo.LineJoin.MITER)

        self.translate(-self.bounds.llx, -self.bounds.lly)

        # Start with a solid-color canvas.
        if bg:
            with self.style(rgb=bg):
                self.rectangle(self.bounds.llx, self.bounds.lly, self.width, self.height)
                self.fill()
项目:my-weather-indicator    作者:atareao    | 项目源码 | 文件源码
def get_surface_from_pixbuf(pixbuf):
    surface = cairo.ImageSurface(
        cairo.FORMAT_ARGB32, pixbuf.get_width(), pixbuf.get_height())
    micairo = cairo.Context(surface)
    micairo.save()
    Gdk.cairo_set_source_pixbuf(micairo, pixbuf, 0, 0)
    micairo.paint()
    micairo.restore()
    return surface
项目:my-weather-indicator    作者:atareao    | 项目源码 | 文件源码
def get_surface_from_file(filename):
    if os.path.exists(filename):
        pixbuf = GdkPixbuf.Pixbuf.new_from_file(filename)
        if pixbuf:
            surface = cairo.ImageSurface(
                cairo.FORMAT_ARGB32, pixbuf.get_width(), pixbuf.get_height())
            context = cairo.Context(surface)
            Gdk.cairo_set_source_pixbuf(context, pixbuf, 0, 0)
            context.paint()
            return surface
    return None
项目:ns3-rdma    作者:bobzhuyb    | 项目源码 | 文件源码
def layout(self, width):
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)
        ctx = cairo.Context(surface)

        # calculate scale delta
        data_delta = self.__hi - self.__lo
        closest = 1
        while (closest*10) < data_delta:
            closest *= 10
        if (data_delta / closest) == 0:
            delta = closest
        elif(data_delta / closest) == 1:
            delta = closest / 10
        else:
            delta = closest
        start = self.__lo - (self.__lo % delta) + delta
        end = self.__hi - (self.__hi % delta)

        self.__delta = delta
        self.__width = width

        # calculate text height
        max_text_height = ctx.text_extents("ABCDEFGHIJKLMNOPQRSTUVWXYZabcedefghijklmnopqrstuvwxyz0123456789")[3]
        self.max_text_height = max_text_height
        height = max_text_height + 10
        self.__height = height
项目:ns3-rdma    作者:bobzhuyb    | 项目源码 | 文件源码
def output_png(self, filename):
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 
                                     self.__data.get_width(), 
                                     self.__data.get_height())
        ctx = cairo.Context(self.__buffer_surface)
        self.__data.draw(ctx)
        surface.write_to_png(filename)
项目:iutils    作者:inconvergent    | 项目源码 | 文件源码
def __init_cairo(self):

    sur = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.n, self.n)
    ctx = cairo.Context(sur)
    ctx.scale(self.n, self.n)

    self.sur = sur
    self.ctx = ctx

    self.clear_canvas()
项目:SegmentationService    作者:jingchaoluan    | 项目源码 | 文件源码
def create_cairo_font_face_for_file(filename, faceindex=0, loadoptions=0):
    global _initialized
    global _freetype_so
    global _cairo_so
    global _ft_lib
    global _surface

    CAIRO_STATUS_SUCCESS = 0
    FT_Err_Ok = 0
    if not _initialized:
        # find shared objects
        _freetype_so = ctypes.CDLL("libfreetype.so.6")
        _cairo_so = ctypes.CDLL("libcairo.so.2")
        # initialize freetype
        _ft_lib = ctypes.c_void_p()
        if FT_Err_Ok != _freetype_so.FT_Init_FreeType(ctypes.byref(_ft_lib)):
          raise OSError("Error initialising FreeType library.")
        _surface = cairo.ImageSurface(cairo.FORMAT_A8, 0, 0)
        _initialized = True
    # create freetype face
    ft_face = ctypes.c_void_p()
    cairo_ctx = cairo.Context(_surface)
    cairo_t = PycairoContext.from_address(id(cairo_ctx)).ctx
    _cairo_so.cairo_ft_font_face_create_for_ft_face.restype = ctypes.c_void_p
    if FT_Err_Ok != _freetype_so.FT_New_Face(_ft_lib, filename, faceindex, ctypes.byref(ft_face)):
        raise Exception("Error creating FreeType font face for " + filename)
    # create cairo font face for freetype face
    cr_face = _cairo_so.cairo_ft_font_face_create_for_ft_face(ft_face, loadoptions)
    if CAIRO_STATUS_SUCCESS != _cairo_so.cairo_font_face_status(cr_face):
        raise Exception("Error creating cairo font face for " + filename)
    _cairo_so.cairo_set_font_face(cairo_t, cr_face)
    if CAIRO_STATUS_SUCCESS != _cairo_so.cairo_status(cairo_t):
        raise Exception("Error creating cairo font face for " + filename)
    face = cairo_ctx.get_font_face()
    return face
项目:SegmentationService    作者:jingchaoluan    | 项目源码 | 文件源码
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()]
项目:python-gui    作者:neovim    | 项目源码 | 文件源码
def _nvim_resize(self, columns, rows):
        da = self._drawing_area
        # create FontDescription object for the selected font/size
        font_str = '{0} {1}'.format(self._font_name, self._font_size)
        self._font, pixels, normal_width, bold_width = _parse_font(font_str)
        # calculate the letter_spacing required to make bold have the same
        # width as normal
        self._bold_spacing = normal_width - bold_width
        cell_pixel_width, cell_pixel_height = pixels
        # calculate the total pixel width/height of the drawing area
        pixel_width = cell_pixel_width * columns
        pixel_height = cell_pixel_height * rows
        gdkwin = da.get_window()
        content = cairo.CONTENT_COLOR
        self._cairo_surface = gdkwin.create_similar_surface(content,
                                                            pixel_width,
                                                            pixel_height)
        self._cairo_context = cairo.Context(self._cairo_surface)
        self._pango_layout = PangoCairo.create_layout(self._cairo_context)
        self._pango_layout.set_alignment(Pango.Alignment.LEFT)
        self._pango_layout.set_font_description(self._font)
        self._pixel_width, self._pixel_height = pixel_width, pixel_height
        self._cell_pixel_width = cell_pixel_width
        self._cell_pixel_height = cell_pixel_height
        self._screen = Screen(columns, rows)
        self._window.resize(pixel_width, pixel_height)
项目:python-gui    作者:neovim    | 项目源码 | 文件源码
def _parse_font(font, cr=None):
    if not cr:
        ims = cairo.ImageSurface(cairo.FORMAT_RGB24, 300, 300)
        cr = cairo.Context(ims)
    fd = Pango.font_description_from_string(font)
    layout = PangoCairo.create_layout(cr)
    layout.set_font_description(fd)
    layout.set_alignment(Pango.Alignment.LEFT)
    layout.set_markup('<span font_weight="bold">A</span>')
    bold_width, _ = layout.get_size()
    layout.set_markup('<span>A</span>')
    pixels = layout.get_pixel_size()
    normal_width, _ = layout.get_size()
    return fd, pixels, normal_width, bold_width
项目:Monocle    作者:Noctem    | 项目源码 | 文件源码
def create(self, stats=conf.IMAGE_STATS):
        if self.time_of_day > 1:
            bg = resource_stream('monocle', 'static/monocle-icons/assets/notification-bg-night.png')
        else:
            bg = resource_stream('monocle', 'static/monocle-icons/assets/notification-bg-day.png')
        ims = cairo.ImageSurface.create_from_png(bg)
        self.context = cairo.Context(ims)
        pokepic = resource_stream('monocle', 'static/monocle-icons/original-icons/{}.png'.format(self.pokemon_id))
        if stats:
            self.draw_stats()
        self.draw_image(pokepic, 204, 224)
        self.draw_name(50 if stats else 120)
        image = TemporaryFile(suffix='.png')
        ims.write_to_png(image)
        return image
项目:py-graphart    作者:dandydarcy    | 项目源码 | 文件源码
def _init_cairo(self):
        '''
        Initialize context and image
        '''
        sur = cairo.ImageSurface(cairo.FORMAT_ARGB32, SIZE, SIZE)
        ctx = cairo.Context(sur)
        ctx.scale(SIZE, SIZE)
        ctx.set_source_rgb(BACK, BACK, BACK)
        ctx.rectangle(0, 0, 1, 1)
        ctx.fill()

        self.sur = sur
        self.ctx = ctx
项目:PyGraphArt    作者:dnlcrl    | 项目源码 | 文件源码
def _init_cairo(self):
        '''
        Initialize context and image
        '''
        sur = cairo.ImageSurface(cairo.FORMAT_ARGB32, SIZE, SIZE)
        ctx = cairo.Context(sur)
        ctx.scale(SIZE, SIZE)
        ctx.set_source_rgb(BACK, BACK, BACK)
        ctx.rectangle(0, 0, 1, 1)
        ctx.fill()

        self.sur = sur
        self.ctx = ctx
项目:sha2017-lenny-face-generator    作者:polyfloyd    | 项目源码 | 文件源码
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
项目:stats    作者:fsr    | 项目源码 | 文件源码
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()
项目:syntrax    作者:kevinpt    | 项目源码 | 文件源码
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]
项目:nvidia-multiple-smi    作者:ClementPinard    | 项目源码 | 文件源码
def draw_icon(machine,color1,color2):
    '''Draws a graph with 2 columns 1 for each percentage (1 is full, 0 is empty)'''
    WIDTH, HEIGHT = 22, 22
    if machine['nGPUs'] > 2:
        WIDTH = 11*machine['nGPUs'] #if more than 1 GPU on a machine, each column is 11px wide (and not 22px)
    surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
    ctx = cairo.Context (surface)
    ctx.scale (WIDTH/machine['nGPUs'], HEIGHT) # Normalizing the canvas coordinates go from (0,0) to (nGPUs,1)

    for i in range(machine['nGPUs']):
        gpu = machine['GPUs'][i]
        percentage1,percentage2 = gpu['utilization']/100,gpu['used_mem']/gpu['memory']
        ctx.rectangle (i, 1-percentage1, 0.5, percentage1) # Rectangle(x0, y0, x1, y1)
        ctx.set_source_rgb(color1[0]/255,color1[1]/255,color1[2]/255)
        ctx.fill ()

        ctx.rectangle (i+0.5, 1-percentage2, 0.5, percentage2) # Rectangle(x0, y0, x1, y1)
        ctx.set_source_rgb(color2[0]/255,color2[1]/255,color2[2]/255)
        ctx.fill ()
    if 'i' not in machine.keys():
        machine['i'] = 0
    png_name = os.path.join(config_folder,machine['name']+str(machine['i'])+'.png')
    machine['i'] = (machine['i']+1)%2

    surface.write_to_png (png_name) # Output to PNG


    return(png_name)
项目:XFWM_theme_creator    作者:Sjc1000    | 项目源码 | 文件源码
def populate(self):
        """populate
        Populates the file list with data from the global var 'files'.
        It reads in their image data and gives them an icon from that.
        """
        main_window = self.get_toplevel()

        for name in files:
            image = files[name]['image']
            pix_width = len(image[0])
            pix_height = len(image)
            if pix_width < 6:
                pix_width = 6
            if pix_height < 6:
                pix_height = 6
            pix_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, pix_width,
                                             pix_height)
            pix_context = cairo.Context(pix_surface)
            pix_context.set_source_rgba(*main_window.paint_background.get_rgba())

            for yi, yv in enumerate(image):
                for xi, xv in enumerate(yv):
                    rgb, var = xv
                    if rgb is not None:
                        pix_context.set_source_rgba(*rgb)
                        pix_context.rectangle(xi, yi, 1, 1)
                        pix_context.fill()
            pixbuf = Gdk.pixbuf_get_from_surface(pix_surface, 0, 0, pix_width,
                                                 pix_height)

            icon = Gtk.IconTheme.get_default().load_icon('image-x-generic', 40, 0)
            self.list.append([pixbuf, name])
        return None
项目:Triplet_Loss_SBIR    作者:TuBui    | 项目源码 | 文件源码
def get_numpy_array(self, size=256, scale=0.333):
        """
        using rsvg library, render the svg into a cairo surface with memory
        defined by a numpy array, effectively rendering the svg to an array
        """
        if self.tree_root is None:
          self.tree_root = self.tree_org.getroot()

        # get the result into a svg object (using rsvg lib)
        svg_object = rsvg.Handle(ET.tostring(self.tree_root))

        # create a numpy array to use as our canvas
        data = np.zeros((size, size, 4), dtype=np.uint8)
        surface = cairo.ImageSurface.create_for_data(
            data, cairo.FORMAT_ARGB32, size, size)

        cr = cairo.Context(surface)

        # fill with solid white and set scale (magic scale number)
        cr.set_source_rgb(1.0, 1.0, 1.0)
        cr.paint()
        cr.scale(scale, scale)

        # render our manipulated svg into cairo surface
        svg_object.render_cairo(cr)

        return data
项目:BinarizationService    作者:jingchaoluan    | 项目源码 | 文件源码
def create_cairo_font_face_for_file(filename, faceindex=0, loadoptions=0):
    global _initialized
    global _freetype_so
    global _cairo_so
    global _ft_lib
    global _surface

    CAIRO_STATUS_SUCCESS = 0
    FT_Err_Ok = 0
    if not _initialized:
        # find shared objects
        _freetype_so = ctypes.CDLL("libfreetype.so.6")
        _cairo_so = ctypes.CDLL("libcairo.so.2")
        # initialize freetype
        _ft_lib = ctypes.c_void_p()
        if FT_Err_Ok != _freetype_so.FT_Init_FreeType(ctypes.byref(_ft_lib)):
          raise OSError("Error initialising FreeType library.")
        _surface = cairo.ImageSurface(cairo.FORMAT_A8, 0, 0)
        _initialized = True
    # create freetype face
    ft_face = ctypes.c_void_p()
    cairo_ctx = cairo.Context(_surface)
    cairo_t = PycairoContext.from_address(id(cairo_ctx)).ctx
    _cairo_so.cairo_ft_font_face_create_for_ft_face.restype = ctypes.c_void_p
    if FT_Err_Ok != _freetype_so.FT_New_Face(_ft_lib, filename, faceindex, ctypes.byref(ft_face)):
        raise Exception("Error creating FreeType font face for " + filename)
    # create cairo font face for freetype face
    cr_face = _cairo_so.cairo_ft_font_face_create_for_ft_face(ft_face, loadoptions)
    if CAIRO_STATUS_SUCCESS != _cairo_so.cairo_font_face_status(cr_face):
        raise Exception("Error creating cairo font face for " + filename)
    _cairo_so.cairo_set_font_face(cairo_t, cr_face)
    if CAIRO_STATUS_SUCCESS != _cairo_so.cairo_status(cairo_t):
        raise Exception("Error creating cairo font face for " + filename)
    face = cairo_ctx.get_font_face()
    return face
项目:BinarizationService    作者:jingchaoluan    | 项目源码 | 文件源码
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()]
项目:deep_ocr    作者:JinpengLI    | 项目源码 | 文件源码
def create_cairo_font_face_for_file(filename, faceindex=0, loadoptions=0):
    global _initialized
    global _freetype_so
    global _cairo_so
    global _ft_lib
    global _surface

    CAIRO_STATUS_SUCCESS = 0
    FT_Err_Ok = 0
    if not _initialized:
        # find shared objects
        _freetype_so = ctypes.CDLL("libfreetype.so.6")
        _cairo_so = ctypes.CDLL("libcairo.so.2")
        # initialize freetype
        _ft_lib = ctypes.c_void_p()
        if FT_Err_Ok != _freetype_so.FT_Init_FreeType(ctypes.byref(_ft_lib)):
          raise OSError("Error initialising FreeType library.")
        _surface = cairo.ImageSurface(cairo.FORMAT_A8, 0, 0)
        _initialized = True
    # create freetype face
    ft_face = ctypes.c_void_p()
    cairo_ctx = cairo.Context(_surface)
    cairo_t = PycairoContext.from_address(id(cairo_ctx)).ctx
    _cairo_so.cairo_ft_font_face_create_for_ft_face.restype = ctypes.c_void_p
    if FT_Err_Ok != _freetype_so.FT_New_Face(_ft_lib, filename, faceindex, ctypes.byref(ft_face)):
        raise Exception("Error creating FreeType font face for " + filename)
    # create cairo font face for freetype face
    cr_face = _cairo_so.cairo_ft_font_face_create_for_ft_face(ft_face, loadoptions)
    if CAIRO_STATUS_SUCCESS != _cairo_so.cairo_font_face_status(cr_face):
        raise Exception("Error creating cairo font face for " + filename)
    _cairo_so.cairo_set_font_face(cairo_t, cr_face)
    if CAIRO_STATUS_SUCCESS != _cairo_so.cairo_status(cairo_t):
        raise Exception("Error creating cairo font face for " + filename)
    face = cairo_ctx.get_font_face()
    return face
项目:deep_ocr    作者:JinpengLI    | 项目源码 | 文件源码
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()]
项目:TikZ    作者:ellisk42    | 项目源码 | 文件源码
def drawTrace(self):
        data = np.zeros((256, 256), dtype=np.uint8)
        surface = cairo.ImageSurface.create_for_data(data,cairo.FORMAT_A8,256,256)
        context = cairo.Context(surface)
        t = [np.zeros((256,256))]
        for l in self.lines:
            l.draw(context)
            t.append(np.flip(data, 0)/255.0)
        return t
项目:Proto_et_Projets    作者:LeBiome    | 项目源码 | 文件源码
def __init__(self,n):

    sur = cairo.ImageSurface(cairo.FORMAT_ARGB32,n,n)
    ctx = cairo.Context(sur)
    ctx.scale(n,n)
    ctx.set_source_rgb(BACK,BACK,BACK)
    ctx.rectangle(0,0,1,1)
    ctx.fill()

    self.sur = sur
    self.ctx = ctx

    self.colors = ((0,0,0))
    self.ncolors = 1
项目:Icon-Requests    作者:bil-elmoussaoui    | 项目源码 | 文件源码
def convert_svg2png(infile, outfile, w, h):
    """
        Converts svg files to png using Cairosvg or Inkscape
        @file_path : String; the svg file absolute path
        @dest_path : String; the png file absolute path
    """
    if use_inkscape:
        p = Popen(["inkscape", "-z", "-f", infile, "-e", outfile,
                   "-w", str(w), "-h", str(h)],
                  stdout=PIPE, stderr=PIPE)
        output, err = p.communicate()
    else:
        handle = Rsvg.Handle()
        svg = handle.new_from_file(infile)
        dim = svg.get_dimensions()

        img = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
        ctx = cairo.Context(img)
        ctx.scale(w / dim.width, h / dim.height)
        svg.render_cairo(ctx)

        png_io = BytesIO()
        img.write_to_png(png_io)
        with open(outfile, 'wb') as fout:
            fout.write(png_io.getvalue())
        svg.close()
        png_io.close()
        img.finish()
项目:paperwork-backend    作者:openpaperwork    | 项目源码 | 文件源码
def __save(self, target_path, pages, progress_cb=dummy_export_progress_cb):
        # XXX(Jflesch): This is a problem. It will fails if someone tries
        # to export to a non-local directory. We should use
        # cairo_pdf_surface_create_for_stream()
        target_path = self.doc.fs.unsafe(target_path)

        pdf_surface = cairo.PDFSurface(target_path,
                                       self.__page_format[0],
                                       self.__page_format[1])
        pdf_context = cairo.Context(pdf_surface)

        pages = [self.doc.pages[x] for x in range(pages[0], pages[1])]
        for page_idx, page in enumerate(pages):
            progress_cb(page_idx, len(pages))
            img = page.img
            if (img.size[0] < img.size[1]):
                (x, y) = (min(self.__page_format[0], self.__page_format[1]),
                          max(self.__page_format[0], self.__page_format[1]))
            else:
                (x, y) = (max(self.__page_format[0], self.__page_format[1]),
                          min(self.__page_format[0], self.__page_format[1]))
            pdf_surface.set_size(x, y)

            logger.info("Adding text to PDF page {} ...".format(page))
            self.__paint_txt(pdf_surface, (x, y), pdf_context, page)
            logger.info("Adding image to PDF page {} ...".format(page))
            self.__paint_img(pdf_surface, (x, y), pdf_context, page)
            pdf_context.show_page()
            logger.info("Page {} ready".format(page))

        progress_cb(len(pages), len(pages))
        return self.doc.fs.safe(target_path)
项目:paperwork-backend    作者:openpaperwork    | 项目源码 | 文件源码
def refresh(self):
        # make the preview

        (tmpfd, tmppath) = tempfile.mkstemp(
            suffix=".pdf",
            prefix="paperwork_export_"
        )
        os.close(tmpfd)

        path = self.__save(tmppath, pages=(self.page_nb, self.page_nb + 1))

        # reload the preview

        file = Gio.File.new_for_uri(path)
        pdfdoc = Poppler.Document.new_from_gfile(file, password=None)
        assert(pdfdoc.get_n_pages() > 0)

        pdfpage = pdfdoc.get_page(0)
        pdfpage_size = pdfpage.get_size()

        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                     int(pdfpage_size[0]),
                                     int(pdfpage_size[1]))
        ctx = cairo.Context(surface)
        pdfpage.render(ctx)
        img = surface2image(surface)

        self.__preview = (path, img)
项目:boids    作者:inconvergent    | 项目源码 | 文件源码
def __init_cairo(self):
    sur = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.n, self.n)
    ctx = cairo.Context(sur)
    ctx.scale(self.n, self.n)
    self.sur = sur
    self.ctx = ctx

    self.clear_canvas()
项目:talks    作者:inconvergent    | 项目源码 | 文件源码
def __init_cairo(self):

    sur = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.n, self.n)
    ctx = cairo.Context(sur)
    ctx.scale(self.n, self.n)

    self.sur = sur
    self.ctx = ctx

    self.clear_canvas()
项目:pyphy-engine    作者:pulkitag    | 项目源码 | 文件源码
def get_ball_im(radius=40, fColor=Color(0.0, 0.0, 1.0), sThick=2, sColor=None):
    '''
        fColor: fill color
        sColor: stroke color
        sThick: stroke thickness
    '''
    sz      = 2*(radius + sThick)
    data    = np.zeros((sz, sz, 4), dtype=np.uint8)
    surface = cairo.ImageSurface.create_for_data(data, 
                            cairo.FORMAT_ARGB32, sz, sz)
    cr      = cairo.Context(surface)
    #Create a transparent source
    cr.set_source_rgba(1.0, 1.0, 1.0, 0.0)
    cr.paint()
    #Create the border
    cx, cy = radius + sThick, radius + sThick
    cr.arc(cx, cy, radius, 0, 2*math.pi)
    cr.set_line_width(sThick)
    if sColor is not None:
        cr.set_source_rgba(sColor.b, sColor.g, sColor.r, sColor.a) 
    else:
        cr.set_source_rgba(0.0, 0.0, 0.0, 1.0) 
    cr.stroke()
    #Fill in the desired color
    cr.set_source_rgba(fColor.b, fColor.g, fColor.r, fColor.a)
    cr.arc(cx, cy, radius, 0, 2*math.pi)
    cr.fill()
    #cr.destroy()
    return cr, data
项目:pyphy-engine    作者:pulkitag    | 项目源码 | 文件源码
def get_rectangle_im(sz=gm.Point(4,100), fColor=Color(1.0, 0.0, 0.0)):
    data    = np.zeros((sz.y_asint(), sz.x_asint(), 4), dtype=np.uint8)
    surface = cairo.ImageSurface.create_for_data(data, 
                            cairo.FORMAT_ARGB32, sz.x_asint(), sz.y_asint())
    cr      = cairo.Context(surface)
    #Create a transparent source
    cr.set_source_rgba(1.0, 1.0, 1.0, 0.0)
    cr.paint()
    # Make rectangle and fill in the desired color
    cr.set_source_rgba(fColor.b, fColor.g, fColor.r, fColor.a)
    cr.rectangle(0, 0, sz.x_asint(), sz.y_asint())
    cr.fill()
    #cr.destroy()
    return cr, data
项目:pyphy-engine    作者:pulkitag    | 项目源码 | 文件源码
def get_arrow_im(pt, fColor=Color(0.0, 0.0, 0.0), arrowWidth=3.0):
    x, y = pt.x(), pt.y()
    sz   = int(np.ceil(max(abs(x), abs(y))))
    data = np.zeros((sz, sz, 4), dtype=np.uint8)
    surface = cairo.ImageSurface.create_for_data(data, 
                            cairo.FORMAT_ARGB32, sz, sz)
    cr      = cairo.Context(surface)
    #Create a transparent source
    cr.set_source_rgba(1.0, 1.0, 1.0, 0.0)
    cr.paint()
    #Start making the arrow
    cr.set_source_rgba(fColor.b, fColor.g, fColor.r, fColor.a)
    if x>=0 and y>=0:
        xSt, ySt = 0, 0
    elif x>0 and y < 0:
        xSt, ySt = 0, sz
    elif x <0 and y<0:
        xSt, ySt = sz, sz
    else:
        xSt, ySt = sz, 0
    stPoint = gm.Point(xSt, ySt) 
    cr.move_to(xSt, ySt)
    pt = pt + stPoint
    dirVec = pt - stPoint
    mag    = dirVec.mag()
    cr.line_to(pt.x(), pt.y())
    cr.set_line_width(arrowWidth)
    side1 = dirVec.rotate_point(-150)
    side1.scale(0.2)
    ang1  = pt + side1  
    cr.line_to(ang1.x(), ang1.y())
    side2 = dirVec.rotate_point(150)
    side2.scale(0.2)
    ang2  = pt + side2
    cr.move_to(pt.x(), pt.y())
    cr.line_to(ang2.x(), ang2.y())
    cr.stroke()
    return cr, data, stPoint
项目:obplayer    作者:openbroadcaster    | 项目源码 | 文件源码
def cairo_context_from_gi(gicr):
    #assert isinstance(gicr, GObject.GBoxed)
    offset = sys.getsizeof(object())  # size of PyObject_HEAD
    # Pull the "boxed" pointer off out and use it as a cairo_t*
    cr_ptr = ctypes.c_void_p.from_address(id(gicr) + offset)
    cr = pycairo_dll.PycairoContext_FromContext(cr_ptr, cairo.Context, None)
    # Add a new ref because the pycairo context will attempt to manage this
    cairo_dll.cairo_reference(cr_ptr)
    return cr
项目:gsTiles    作者:schmidtc    | 项目源码 | 文件源码
def getContext(surface, tx=0, ty=0, zoom=0):
    ctx = cairo.Context(surface)
    ctx.set_antialias(cairo.ANTIALIAS_NONE)
    ctx.set_line_join(cairo.LINE_JOIN_BEVEL)
    return ctx