本文整理汇总了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()
示例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
)
示例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)
示例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()
示例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
示例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
示例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
示例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()
示例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)
示例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)
示例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)
示例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
示例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!"
示例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)
示例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