當前位置: 首頁>>代碼示例>>Python>>正文


Python cairo.Context類代碼示例

本文整理匯總了Python中cairo.Context的典型用法代碼示例。如果您正苦於以下問題:Python Context類的具體用法?Python Context怎麽用?Python Context使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Context類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: convert_svg2png

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 = ImageSurface(FORMAT_ARGB32, w, h)
        ctx = 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()
開發者ID:Ewaryst,項目名稱:circle-core,代碼行數:28,代碼來源:gen.py

示例2: layout

    def layout(self, context: cairo.Context):
        super().layout(context)
        context.set_font_size(self.font_size)
        xb, yb, w, h, xa, ya = context.text_extents(self.title)
        font_shape = Rectangle(Point(h/2 + self.distance, self.distance), xa, h)
        self.__title_start_point = Point(font_shape.start.x,
                                         font_shape.start.y + h)
        outer_font_box = DrawableRectangle(
            Point(font_shape.start.x - self.distance,
                  font_shape.start.y - self.distance),
            font_shape.width + 2 * self.distance,
            font_shape.height + 2 * self.distance
        )
        self.__outer_font_box = outer_font_box
        wrapper_shape = DrawableRectangle(
            Point(0, outer_font_box.start.y + outer_font_box.height / 2),
            outer_font_box.start.x + max(
                outer_font_box.width,
                self.widget.shape.width
            ) + self.distance,
            outer_font_box.height/2 + 2*self.distance +
                self.widget.shape.height
        )

        self.widget.set_translate(
            outer_font_box.start.x,
            outer_font_box.start.y + outer_font_box.height + self.distance
        )

        self.__wrapper_shape = wrapper_shape
        self.shape = DrawableRectangle(
            Point(0, 0),
            wrapper_shape.width,
            wrapper_shape.start.y + wrapper_shape.height
        )
開發者ID:gcali,項目名稱:crucipixel,代碼行數:35,代碼來源:input.py

示例3: renegerate_overlay_buffer

    def renegerate_overlay_buffer(self):
        image = ImageSurface(cairo.FORMAT_ARGB32, self.video_width, self.video_height)
        context = Context(image)
        text = "Foo bar 123"
        font = pango.FontDescription('sans normal 22')
        text_offset = [6, 6]

        textOverflowed = False
        if text:
            pcContext = pangocairo.CairoContext(context)
            pangoLayout = pcContext.create_layout()
            font = pango.FontDescription('sans normal 22')
            pangoLayout.set_font_description(font)
    
            context.move_to(text_offset[0]+2, text_offset[1]+2)
            pangoLayout.set_markup('<span foreground="black" >%s</span>' % text)
            pcContext.show_layout(pangoLayout)
            context.move_to(text_offset[0], text_offset[1])
            pangoLayout.set_markup('<span foreground="white" >%s</span>' % text)
            pcContext.show_layout(pangoLayout)
    
            textWidth, textHeight = pangoLayout.get_pixel_size()
        
        self.overlay_buffer = image.get_data()
        print "overlay_buffer size: %d" % len(self.overlay_buffer)
開發者ID:HelsinkiHacklab,項目名稱:cambot,代碼行數:25,代碼來源:cairo_overlay_pango_text.py

示例4: convert_to_png

    def convert_to_png(input_file, output_file, width=None, height=None):
        """Convert svg to png."""
        if width and height:
            handle = Rsvg.Handle()
            svg = handle.new_from_file(input_file)
            dim = svg.get_dimensions()

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

            png_io = BytesIO()
            img.write_to_png(png_io)
            with open(output_file, 'wb') as fout:
                fout.write(png_io.getvalue())
            fout.close()
            svg.close()
            png_io.close()
            img.finish()
        else:
            with open(input_file, "r") as content_file:
                svg = content_file.read()
            content_file.close()
            fout = open(output_file, "wb")
            svg2png(bytestring=bytes(svg, "UTF-8"), write_to=fout)
            fout.close()
開發者ID:bil-elmoussaoui,項目名稱:Hardcode-Tray,代碼行數:27,代碼來源:cairosvg.py

示例5: __missing__

 def __missing__(self, zoom):
     zoomfac    = (1 + 2*self._r)*zoom
     self[zoom] = SVGC = ImageSurface(FORMAT_ARGB32, ceil(zoomfac*self._h), ceil(zoomfac*self._k))
     sccr = Context(SVGC)
     sccr.scale(zoom, zoom)
     sccr.translate(self._uh, self._uk)
     self._paint_function(sccr)
     return SVGC
開發者ID:kelvin13,項目名稱:Knockout,代碼行數:8,代碼來源:vectorcache.py

示例6: setup_doc

def setup_doc(name):
    '''
    '''
    doc = PDFSurface(name, sheet_width*ptpin, sheet_height*ptpin)
    ctx = Context(doc)
    ctx.scale(ptpin, ptpin)
    
    set_font_face_from_file(ctx, 'DejaVuSerifCondensed.ttf')
    
    return doc, ctx
開發者ID:imclab,項目名稱:4up,代碼行數:10,代碼來源:layout.py

示例7: create_cairo_font_face_for_file

def create_cairo_font_face_for_file(filename, faceindex=0, loadoptions=0):
    """
    
        http://cairographics.org/freetypepython
    """

    CAIRO_STATUS_SUCCESS = 0
    FT_Err_Ok = 0

    # find shared objects
    _freetype_so = ctypes.CDLL('libfreetype.so.6')
    _cairo_so = ctypes.CDLL('libcairo.so.2')

    _cairo_so.cairo_ft_font_face_create_for_ft_face.restype = ctypes.c_void_p
    _cairo_so.cairo_ft_font_face_create_for_ft_face.argtypes = [ ctypes.c_void_p, ctypes.c_int ]
    _cairo_so.cairo_set_font_face.argtypes = [ ctypes.c_void_p, ctypes.c_void_p ]
    _cairo_so.cairo_font_face_status.argtypes = [ ctypes.c_void_p ]
    _cairo_so.cairo_status.argtypes = [ ctypes.c_void_p ]

    # initialize freetype
    _ft_lib = ctypes.c_void_p()
    if FT_Err_Ok != _freetype_so.FT_Init_FreeType(ctypes.byref(_ft_lib)):
      raise "Error initialising FreeType library."

    class PycairoContext(ctypes.Structure):
        _fields_ = [("PyObject_HEAD", ctypes.c_byte * object.__basicsize__),
                    ("ctx", ctypes.c_void_p),
                    ("base", ctypes.c_void_p)]

    _surface = ImageSurface(FORMAT_A8, 0, 0)

    # create freetype face
    ft_face = ctypes.c_void_p()
    cairo_ctx = 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
開發者ID:brendancol,項目名稱:fieldpapers-1,代碼行數:54,代碼來源:svgutils.py

示例8: on_draw

 def on_draw(self, widget: Widget, context: cairo.Context):
     for child in self.list:
         if child.visible:
             context.save()
             context.transform(child.fromWidgetCoords)
             if child.is_clip_set():
                 rectangle = child.clip_rectangle
                 context.rectangle(rectangle.start.x,rectangle.start.y,
                                   rectangle.width,rectangle.height)
                 context.clip()
             child.on_draw(self,context)
             context.restore()
開發者ID:gcali,項目名稱:crucipixel,代碼行數:12,代碼來源:containers.py

示例9: illustrate

 def illustrate(self, surface):
     if self.art != None:
         illustration = Context(surface)
         illustration.scale(0.6, 0.6)
         illustration.translate(self.w / 6, self.h / 6)
         self.art.render_cairo(illustration)
         illustration.translate(self.w * 4 / 3, self.h * 4 / 3)
         illustration.rotate(pi)
         self.art.render_cairo(illustration)
開發者ID:,項目名稱:,代碼行數:9,代碼來源:

示例10: on_draw

 def on_draw(self, widget: Widget, context: cairo.Context):
     self.shape.draw_on_context(context)
     context.set_source_rgb(*global_constants.background)
     context.fill_preserve()
     context.set_source_rgb(0, 0, 0)
     context.stroke()
     super().on_draw(widget, context)
開發者ID:gcali,項目名稱:crucipixel,代碼行數:7,代碼來源:zoom.py

示例11: set_shape_from_context

    def set_shape_from_context(self, context: cairo.Context):
        label = self.label
        padding = self.padding
        context.set_font_size(self.font_size)
        xb, yb, w, h, xa, ya = context.text_extents(label)
        width = padding * 2 + xa
        height = padding * 2 + h
        height = max(height, self.min_height)

        if self.origin == self.LEFT:
            start = Point(0, 0)
        elif self.origin == self.CENTER:
            start = Point(-width/2, 0)
        else:
            start = Point(-width, 0)
        self.shape = DrawableRoundedRectangle(start, width, height)
開發者ID:gcali,項目名稱:crucipixel,代碼行數:16,代碼來源:buttons.py

示例12: _scale_down

    def _scale_down(self, handle, ratio):
        xsize, ysize = self.size
        if ratio >= 1.0:
            # Convert
            surface = ImageSurface(FORMAT_ARGB32, xsize, ysize)
            ctx = Context(surface)
        else:
            # Scale
            xsize, ysize = int(xsize * ratio), int(ysize * ratio)
            surface = ImageSurface(FORMAT_ARGB32, xsize, ysize)
            ctx = Context(surface)
            ctx.scale(ratio, ratio)

        # Render
        handle.render_cairo(ctx)

        # Transform to a PIL image for further manipulation
        size = (xsize, ysize)
        im = frombuffer('RGBA', size, surface.get_data(), 'raw', 'BGRA', 0, 1)
        surface.finish()

        return im, xsize, ysize
開發者ID:hforge,項目名稱:itools,代碼行數:22,代碼來源:image.py

示例13: MapSurface

class MapSurface(object):
    """wrapper to render the map to svg/png"""

    def __init__(self, hexmap=None, filename=None, width=None, height=None, size=None):
        self.hexmap = hexmap
        if self.hexmap is None:
            raise ValueError("No map was passed to {}".format(self.__class__.__name__))
        self.surface_name = filename or "test.svg"
        self.size = size or 32.0
        self.surface_width = width
        if self.surface_width is None:
            self.surface_width = (self.hexmap.map.cols + .5) * self.size * SQRT3
        self.surface_height = height
        if self.surface_height is None:
            self.surface_height = (self.hexmap.map.rows * 1.5 + .25) * self.size
        self.layer = []

        # build base map
        self.surface = SVGSurface(self.surface_name + ".svg", self.surface_width, self.surface_height)
        self.context = Context(self.surface)
        # background: magenta
        self.context.save()
        self.context.set_source_rgb(1.0, 0.0, 1.0)
        self.context.paint()
        self.context.restore()

    def add_layer(self, renderer_cls, position=None):
        if not position:
            self.layer.append(renderer_cls(self))
        else:
            self.layer.insert(position, renderer_cls(self))

    def render(self):
        print "Rendering {} ({}x{})".format(self.surface_name, self.surface_width, self.surface_height)
        for renderer in self.layer:
            renderer.render()

    def finalise(self, with_png=False):
        print "finalising:"
        if with_png is True:
            print "PNG"
            self.surface.write_to_png(self.surface_name + ".png")
        print "SVG"
        self.surface.finish()
        print "DONE!"
開發者ID:,項目名稱:,代碼行數:45,代碼來源:

示例14: glyphs

def glyphs(*args, **kwargs):

    options = Options(infname='data/vorttest.txt', saveas='output/part1/',
            outfname='vorttest.png', scale=100., seed_num=20, stepsize=.01,
            steps=5, directions=1, norm=False, line_width=.5)
    options.update(kwargs)

    print >> log, options.infname

    if not path.exists(options.saveas): os.makedirs(options.saveas)

    (xmin, ymin), (xmax, ymax), uv = read2vecs(options.infname)

    width, height = xmax - xmin, ymax - ymin

    def index2world(points, xmin=xmin, ymin=ymin, scale=options.scale,
            debug=False):
        if debug: 
            print "index2world:",
            print xscale, yscale, points.dtype
        if debug: print points,
        points[:,0] -= xmin
        if debug: print points,
        points[:,1] -= ymin
        if debug: print points,
        points *= scale
        if debug: print points

    if 'seed' in options:
        seed = options.seed
    else: 
        seed = product(np.linspace(xmin, xmax, num=options.seed_num), 
                np.linspace(ymin, ymax, num=options.seed_num))


    ctx = Context(ImageSurface(cairo.FORMAT_ARGB32, int(options.scale * width),
        int(options.scale * height)))

    ctx.set_source_rgba(0,0,0)
    ctx.set_line_width(options.line_width)
    for s in seed:
        points = sline(uv, (xmin, ymin), (xmax, ymax), np.array(s),
            options.stepsize, options.steps, options.norm, options.directions)
        print >> log, points
        index2world(points)
        print >> log, points
        draw_arrow(ctx, points, arrowhead_size=2)

    with open(path.join(options.saveas, options.outfname), 'w') as outf:
        ctx.get_target().write_to_png(outf)
開發者ID:damonwang,項目名稱:scivis-proj4,代碼行數:50,代碼來源:proj4.py

示例15: __init__

 def __init__(self, width, height):
     self.xform = lambda x, y: (x, y)
 
     self.img = ImageSurface(FORMAT_RGB24, width, height)
     self.ctx = Context(self.img)
     
     self.ctx.move_to(0, 0)
     self.ctx.line_to(width, 0)
     self.ctx.line_to(width, height)
     self.ctx.line_to(0, height)
     self.ctx.line_to(0, 0)
     
     self.ctx.set_source_rgb(1, 1, 1)
     self.ctx.fill()
     
     self.width = width
     self.height = height
開發者ID:Katiesun,項目名稱:Skeletron,代碼行數:17,代碼來源:draw.py


注:本文中的cairo.Context類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。