def __init__(self, filename, entity, options): self.color = (0, 0, 0) self.factor = 1 self.background_color = (0, 0, 0) self.analyse_options(options) self.surface = cairo.SVGSurface(filename, 10, 10) self.context = cairo.Context(self.surface) self.factor = 1 self.height = self.compute_height(entity) self.width = self.compute_width(entity) self.line_length = default_line_length self.surface = cairo.PDFSurface( filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2) self.context = cairo.Context(self.surface) self.compute_wire_length(entity) if options.format.lower() == "svg": self.factor = 1 self.surface = cairo.SVGSurface( filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2) if options.format.lower() == "pdf": self.factor = 1 self.surface = cairo.PDFSurface( filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2) if options.format.lower() == "ps": self.factor = 1 self.surface = cairo.PSSurface( filename, self.width + self.line_length * 2 + bbox_w_margin * 2, self.height + bbox_h_margin * 2) if options.format.lower() == "png": self.factor = float( options.width / (self.width + self.factor * self.line_length * 2 + self.factor * bbox_w_margin * 2)) stride = cairo.ImageSurface.format_stride_for_width( cairo.FORMAT_ARGB32, 10000) data = bytearray(stride * 10000) # stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32, int(self.width)+1) # data = bytearray(stride * int(self.height)) self.surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, int(self.factor * self.width + self.factor * self.line_length * 2 + self.factor * bbox_w_margin * 2), int(self.factor * self.height + self.factor * bbox_h_margin * 2), data, stride) self.context = cairo.Context(self.surface) self.draw_background(self.context) self.draw_entity(entity) self.surface.write_to_png(options.filename)
def genSVG(height, width): """Outputs a .SVG file of the mapped hex tiles""" surface = cairo.SVGSurface("outputs/latest.svg", width, height) surface.set_document_unit(cairo.SVG_UNIT_MM) ctxt = cairo.Context(surface) ctxt.translate(10, 10) def drawHex(point, hexHeight, colours): verts = [(point[0], point[1] + hexHeight / 2), (point[0] + math.sqrt(3) * hexHeight / 4, point[1] + hexHeight / 4), (point[0] + math.sqrt(3) * hexHeight / 4, point[1] - hexHeight / 4), (point[0], point[1] - hexHeight / 2), (point[0] - math.sqrt(3) * hexHeight / 4, point[1] - hexHeight / 4), (point[0] - math.sqrt(3) * hexHeight / 4, point[1] + hexHeight / 4)] for coord in verts: ctxt.line_to(coord[0], coord[1]) ctxt.close_path() ctxt.set_source_rgb(0, 0, 0) ctxt.set_line_width(1) ctxt.stroke_preserve() ctxt.set_source_rgb(*colours[point[2]]) ctxt.fill() return drawHex
def output_file(ctx): root, extension = os.path.splitext(target) if file_number: filename = '%s_%04d%s' % (root, file_number, extension) else: filename = target extension = extension.lower() if extension == '.png': surface = ctx.get_target() surface.write_to_png(target) elif extension == '.pdf': target_ctx = cairo.Context( cairo.PDFSurface(filename, *self.size_or_default())) target_ctx.set_source_surface(ctx.get_target()) target_ctx.paint() elif extension in ('.ps', '.eps'): target_ctx = cairo.Context( cairo.PSSurface(filename, *self.size_or_default())) if extension == '.eps': target_ctx.set_eps(extension='.eps') target_ctx.set_source_surface(ctx.get_target()) target_ctx.paint() elif extension == '.svg': target_ctx = cairo.Context( cairo.SVGSurface(filename, *self.size_or_default())) target_ctx.set_source_surface(ctx.get_target()) target_ctx.paint() return filename
def draw_on_coxeter_plane( P, nodes1, nodes2, svgpath=None, image_size=600, linewidth=0.0012, markersize=0.015 ): """ Project the vertices of a polytope `P` to its Coxeter plane and draw the pattern to a svg image. The most important parameters are `nodes1` and `nodes2`, they can be of lists/tuples/sets type and must partition the Coxeter diagram of `P` into two disjoint sets such that the nodes in each set are mutually orthogonal with each other. """ P.build_geometry() M = P.mirrors C = np.dot(M, M.T) # Cartan matrix eigenvals, eigenvecs = np.linalg.eigh(C) # get the eigenvector with largest (or smallest) eigenvalue v = eigenvecs[:, 0] # a basis of the Coxeter plane mu_a = np.sum([v[i] * M[i] for i in nodes1], axis=0) mu_b = np.sum([v[j] * M[j] for j in nodes2], axis=0) # make them orthogonal mu_a = helpers.normalize(mu_a) mu_b -= np.dot(mu_b, mu_a) * mu_a mu_b = helpers.normalize(mu_b) vertices_2d = [(np.dot(mu_a, x), np.dot(mu_b, x)) for x in P.vertices_coords] # draw on image if svgpath is None: svgpath = P.__class__.__name__ + ".svg" extent = 0.99 surface = cairo.SVGSurface(svgpath, image_size, image_size) ctx = cairo.Context(surface) ctx.scale(image_size / (extent * 2.0), -image_size / (extent * 2.0)) ctx.translate(extent, -extent) ctx.set_source_rgb(1, 1, 1) ctx.paint() ctx.set_line_width(linewidth) # draw edges for elist in P.edge_indices: for i, j in elist: x1, y1 = vertices_2d[i] x2, y2 = vertices_2d[j] ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(linewidth) ctx.move_to(x1, y1) ctx.line_to(x2, y2) ctx.stroke() # draw the vertices as circles ctx.set_line_width(linewidth * 2) for x, y in vertices_2d: ctx.arc(x, y, markersize, 0, 2 * np.pi) ctx.set_source_rgb(1, 0, 0) ctx.fill_preserve() ctx.set_source_rgb(0, 0, 0) ctx.stroke() surface.finish()
def _make_vector_surface(self, output_path, image_format, image_width, crop_margin): """ Make a vector surface in the appropriate format and with the appropriate size depending on whether or not there is a crop margin. In a vector image, 1 screen pixel is scaled to a certain number of points, such that the figure as a whole will conform to a certain physical size. """ if crop_margin is None: scale = image_width / self.screen_width image_height = self.screen_height * scale else: crop_margin = _mm_to_pts(crop_margin) if crop_margin > image_width / 3: raise ValueError( "The crop margin set on this image is too large for the image width. Increase the image width or decrease the crop margin." ) scale = (image_width - crop_margin * 2) / ( self._block_extents[2] - self._block_extents[0] ) image_height = ( self._block_extents[3] - self._block_extents[1] ) * scale + crop_margin * 2 if image_format == "PDF": surface = _cairo.PDFSurface(output_path, image_width, image_height) surface.set_metadata(_cairo.PDF_METADATA_CREATOR, f"eyekit {__version__}") elif image_format == "EPS": surface = _cairo.PSSurface(output_path, image_width, image_height) surface.set_eps(True) elif image_format == "SVG": surface = _cairo.SVGSurface(output_path, image_width, image_height) surface.set_device_scale(scale, scale) return surface, scale, crop_margin
def __init__( self, image=None, # PIL image size=None, ctx=None, imageType=None, # determines file type fileName=None, # if set determines output file name ): """ Canvas can be used in four modes: 1) using the supplied PIL image 2) using the supplied cairo context ctx 3) writing to a file fileName with image type imageType 4) creating a cairo surface and context within the constructor """ self.image = None self.imageType = imageType if image is not None: try: imgd = getattr(image, 'tobytes', image.tostring)("raw", "BGRA") except SystemError: r, g, b, a = image.split() mrg = Image.merge("RGBA", (b, g, r, a)) imgd = getattr(mrg, 'tobytes', mrg.tostring)("raw", "RGBA") a = array.array('B', imgd) stride = image.size[0] * 4 surface = cairo.ImageSurface.create_for_data( a, cairo.FORMAT_ARGB32, image.size[0], image.size[1], stride) ctx = cairo.Context(surface) size = image.size[0], image.size[1] self.image = image elif ctx is None and size is not None: if hasattr(cairo, "PDFSurface") and imageType == "pdf": surface = cairo.PDFSurface(fileName, size[0], size[1]) elif hasattr(cairo, "SVGSurface") and imageType == "svg": surface = cairo.SVGSurface(fileName, size[0], size[1]) elif hasattr(cairo, "PSSurface") and imageType == "ps": surface = cairo.PSSurface(fileName, size[0], size[1]) elif imageType == "png": surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size[0], size[1]) else: raise ValueError( "Unrecognized file type. Valid choices are pdf, svg, ps, and png" ) ctx = cairo.Context(surface) ctx.set_source_rgb(1, 1, 1) ctx.paint() else: surface = ctx.get_target() if size is None: try: size = surface.get_width(), surface.get_height() except AttributeError: size = None self.ctx = ctx self.size = size self.surface = surface self.fileName = fileName
def fileformat(filename, width, height): ''' figure out the output image format Args: filename: output filename, which will raise an error if it does not end in one of '.pdf', '.png', '.ps', or '.svg' width: width of the output image, in pixels height: height of the output image, in pixels Returns: tuple of cairo.Surface and filetype string e.g. 'pdf' or 'png' ''' if filename is not None: _, ext = os.path.splitext(filename) if not ext: ext = '.png' ext = ext[1:].lower() else: ext = None assert ext in ['png', 'pdf', 'ps', 'svg', None], 'unknown format: .{}'.format(ext) if ext == 'pdf': surface = cairo.PDFSurface(filename, width, height) elif ext == 'svg': surface = cairo.SVGSurface(filename, width, height) elif ext == 'ps': surface = cairo.PSSurface(filename, width, height) else: surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) return ext, surface
def __init__(self, path: Path, surface_type: str, width: float, height: float, scale: float = 1): self.width = width self.height = height self.scale = scale self.path_as_posix = path.as_posix() if surface_type == 'pdf': surface = cairo.PDFSurface(self.path_as_posix, width, height) elif surface_type == 'svg': surface = cairo.SVGSurface(self.path_as_posix, width, height) elif surface_type == 'png': surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(width), int(height)) else: raise Exception('Unexpected Format: %s' % surface_type) context = cairo.Context(surface) self.surface = surface self.context = context if isinstance(self.surface, cairo.ImageSurface): self.context.scale( CanvasUnit.from_pt(1).px * self.scale, CanvasUnit.from_pt(1).px * self.scale)
def create_new_surface(file_format, target=None, width=1024, height=768): """ Create a new surface of the specified `file_format`: "png" for :class:`ImageSurface` "svg" for :class:`SVGSurface` "pdf" for :class:`PDFSurface` "ps" for :class:`PSSurface` The surface will be written to the `target` parameter , which can be a path to save the surface to, or file-like object with a `write()` method. You can also optionally specify the `width` and `height` of the generated surface if you know what it is; otherwise a default size of 1024 by 768 is used. """ file_format = file_format.lower() if file_format == 'png': surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, int(width), int(height)) elif file_format == 'svg': surface = cairo.SVGSurface(target, width, height) elif file_format == 'pdf': surface = cairo.PDFSurface(target, width, height) elif file_format == 'ps': surface = cairo.PSSurface(target, width, height) else: raise ValueError( 'Invalid value "{0}" for type parameter; valid values are "png", "svg", "pdf", and "ps".'.format(type)) return surface
def show(self, format='png', as_data=False): '''Returns an Image object of the current surface. Used for displaying output in Jupyter notebooks. Adapted from the cairo-jupyter project.''' import cairocffi as cairo from io import BytesIO b = BytesIO() if format == 'png': from IPython.display import Image surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.WIDTH, self.HEIGHT) self.snapshot(surface) surface.write_to_png(b) b.seek(0) data = b.read() if as_data: return data else: return Image(data) elif format == 'svg': from IPython.display import SVG surface = cairo.SVGSurface(b, self.WIDTH, self.HEIGHT) surface.finish() b.seek(0) data = b.read() if as_data: return data else: return SVG(data)
def render_as_svg(self, output): paths = [] for simplice in self.tri.simplices: for i, _ in enumerate(simplice): paths.append([simplice[i - 1], simplice[i]]) # Filtering list for repeated paths paths = self.filter_path_list(paths) fo = open(output, 'wb') surface_svg = cairo.SVGSurface(fo, self.image.width, self.image.height) context = cairo.Context(surface_svg) context.set_line_cap(cairo.LINE_CAP_ROUND) context.set_line_join(cairo.LINE_JOIN_ROUND) context.set_line_width(0.5) with context: context.set_source_rgb(1, 1, 1) context.paint() # Finally drawing paths for path in paths: x, y = self.tri.points[path[0]] context.move_to(x, y) x, y = self.tri.points[path[1]] context.line_to(x, y) context.stroke() surface_svg.finish()
def _save(self, fo, fmt, **kwargs): # save PDF/PS/SVG orientation = kwargs.get('orientation', 'portrait') dpi = 72 self.figure.dpi = dpi w_in, h_in = self.figure.get_size_inches() width_in_points, height_in_points = w_in * dpi, h_in * dpi if orientation == 'landscape': width_in_points, height_in_points = ( height_in_points, width_in_points) if fmt == 'ps': if not hasattr(cairo, 'PSSurface'): raise RuntimeError('cairo has not been compiled with PS ' 'support enabled') surface = cairo.PSSurface(fo, width_in_points, height_in_points) elif fmt == 'pdf': if not hasattr(cairo, 'PDFSurface'): raise RuntimeError('cairo has not been compiled with PDF ' 'support enabled') surface = cairo.PDFSurface(fo, width_in_points, height_in_points) elif fmt in ('svg', 'svgz'): if not hasattr(cairo, 'SVGSurface'): raise RuntimeError('cairo has not been compiled with SVG ' 'support enabled') if fmt == 'svgz': if isinstance(fo, six.string_types): fo = gzip.GzipFile(fo, 'wb') else: fo = gzip.GzipFile(None, 'wb', fileobj=fo) surface = cairo.SVGSurface(fo, width_in_points, height_in_points) else: warnings.warn("unknown format: %s" % fmt) return # surface.set_dpi() can be used renderer = RendererCairo(self.figure.dpi) renderer.set_width_height(width_in_points, height_in_points) renderer.set_ctx_from_surface(surface) ctx = renderer.gc.ctx if orientation == 'landscape': ctx.rotate(np.pi/2) ctx.translate(0, -height_in_points) # cairo/src/cairo_ps_surface.c # '%%Orientation: Portrait' is always written to the file header # '%%Orientation: Landscape' would possibly cause problems # since some printers would rotate again ? # TODO: # add portrait/landscape checkbox to FileChooser self.figure.draw(renderer) ctx.show_page() surface.finish() if fmt == 'svgz': fo.close()
def __enter__(msk): size_in_pixels = self.size_in_pixels msk.surface = cairo.SVGSurface(None, size_in_pixels[0], size_in_pixels[1]) msk.ctx = cairo.Context(msk.surface) msk.ctx.translate(-self.origin_in_pixels[0], -self.origin_in_pixels[1]) return msk
def draw_page(bot_clip, top_clip, ds, ms_values, scale, formations, legend=None, filename=None, current_data=None, annotation=None): global last_glc_height, log_settings last_glc_height = None height = top_clip - bot_clip top_margin = 24 bot_margin = 5 total_height_pt = scale * height + top_margin + bot_margin if filename is None: filename = 'output/ffq%04d' % bot_clip if log_settings.pdf_output: surface = cairo.PDFSurface(filename + '.pdf', mm_to_pt(160), total_height_pt) else: surface = cairo.SVGSurface(filename + '.svg', mm_to_pt(160), total_height_pt) ctx = cairo.Context(surface) ctx.select_font_face(log_settings.font_name) if annotation is not None: draw_annotation(ctx, 20, annotation[0], annotation[1]) draw_magsus(ctx, height + top_margin / scale, bot_clip, top_clip, scale, bot_clip, ms_values) for i in range(0, len(ds)): if i > 0: above = ds[i - 1] else: above = None d = ds[i] if d.bot >= bot_clip and d.bot + d.thick <= top_clip: ds[i].draw(height + top_margin / scale, ctx, scale, above, bot_clip) draw_axis(height + top_margin / scale, ctx, 0., height, 100., scale, bot_clip) draw_header(ctx, top_margin - 10) if log_settings.decs_incs_list is not None: draw_decsincs_graph(ctx, height + top_margin / scale, bot_clip, top_clip, scale, bot_clip) for (name, bot, top) in formations: draw_formation(ctx, height + top_margin / scale, bot_clip, top_clip, scale, bot_clip, name, bot, top) if current_data is not None: page, currents = current_data draw_currents(ctx, 400, page, currents) if legend is not None: draw_legend(ctx, *legend) surface.finish()
def textwidth(self, text, config): """Calculates the width of the specified text. """ surface = cairo.SVGSurface(None, 1280, 200) ctx = cairo.Context(surface) ctx.select_font_face(config['font_face'], cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) ctx.set_font_size(int(config['font_size'])) return ctx.text_extents(text)[2] + 2
def __init__(self, filename, width=600, height=600): # We expect the object to be in normalized screen space self.width, self.height = width, height self.surface = cairo.SVGSurface(filename, width, height) self.cr = cairo.Context(self.surface) self.cr.translate(width / 2, height / 2) self.cr.scale(1, -1) self.cr.translate(-width / 2, -height / 2)
def set_bounds(self, bounds): origin_in_inch = (bounds[0][0], bounds[1][0]) size_in_inch = (abs(bounds[0][1] - bounds[0][0]), abs(bounds[1][1] - bounds[1][0])) size_in_pixels = map(mul, size_in_inch, self.scale) self.origin_in_pixels = tuple(map(mul, origin_in_inch, self.scale)) if self.origin_in_pixels is None else self.origin_in_pixels self.size_in_pixels = size_in_pixels if self.size_in_pixels is None else self.size_in_pixels if self.surface is None: self.surface_buffer = tempfile.NamedTemporaryFile() self.surface = cairo.SVGSurface(self.surface_buffer, size_in_pixels[0], size_in_pixels[1]) self.ctx = cairo.Context(self.surface) self.ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD) self.ctx.scale(1, -1) self.ctx.translate(-(origin_in_inch[0] * self.scale[0]), (-origin_in_inch[1]*self.scale[0]) - size_in_pixels[1]) self.mask = cairo.SVGSurface(None, size_in_pixels[0], size_in_pixels[1]) self.mask_ctx = cairo.Context(self.mask) self.mask_ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD) self.mask_ctx.scale(1, -1) self.mask_ctx.translate(-(origin_in_inch[0] * self.scale[0]), (-origin_in_inch[1]*self.scale[0]) - size_in_pixels[1])
def Surface(NAME, TYPE, Size): # NAME: Song Name (with page#?) # TYPE: {PDF, SVG} # Size: {A3, A4, B4, B3} if TYPE == 'PDF': return cairo.Context(cairo.PDFSurface(NAME + '.pdf', Size[0], Size[1])) elif TYPE == 'SVG': return cairo.Context(cairo.SVGSurface(NAME + '.svg', Size[0], Size[1]))
def draw_surface(fasta_dict, num_motifs): num_genes = len(fasta_dict) # width is length of longest sequence plus 100 (for some extra white space) WIDTH = len(sorted(fasta_dict.values(), key=len)[-1]) + 100 # height is the y_offset * number of genes HEIGHT = 100 * num_genes + 20 * num_motifs surface = cairo.SVGSurface("plot.svg", WIDTH, HEIGHT) context = cairo.Context(surface) return (context)
def _save(self, fo, fmt, **kwargs): # save PDF/PS/SVG orientation = kwargs.get('orientation', 'portrait') dpi = 72 self.figure.dpi = dpi w_in, h_in = self.figure.get_size_inches() width_in_points, height_in_points = w_in * dpi, h_in * dpi if orientation == 'landscape': width_in_points, height_in_points = (height_in_points, width_in_points) if fmt == 'ps': if not hasattr(cairo, 'PSSurface'): raise RuntimeError('cairo has not been compiled with PS ' 'support enabled') surface = cairo.PSSurface(fo, width_in_points, height_in_points) elif fmt == 'pdf': if not hasattr(cairo, 'PDFSurface'): raise RuntimeError('cairo has not been compiled with PDF ' 'support enabled') surface = cairo.PDFSurface(fo, width_in_points, height_in_points) elif fmt in ('svg', 'svgz'): if not hasattr(cairo, 'SVGSurface'): raise RuntimeError('cairo has not been compiled with SVG ' 'support enabled') if fmt == 'svgz': if isinstance(fo, str): fo = gzip.GzipFile(fo, 'wb') else: fo = gzip.GzipFile(None, 'wb', fileobj=fo) surface = cairo.SVGSurface(fo, width_in_points, height_in_points) else: warnings.warn("unknown format: %s" % fmt, stacklevel=2) return # surface.set_dpi() can be used renderer = RendererCairo(self.figure.dpi) renderer.set_width_height(width_in_points, height_in_points) renderer.set_ctx_from_surface(surface) ctx = renderer.gc.ctx if orientation == 'landscape': ctx.rotate(np.pi / 2) ctx.translate(0, -height_in_points) # Perhaps add an '%%Orientation: Landscape' comment? self.figure.draw(renderer) ctx.show_page() surface.finish() if fmt == 'svgz': fo.close()
def __init__(self, img_format="png", output="page", width=0.15, height=0.15, dots_per_inch=dots_per_inch): """ A thin wrapper to produce vector graphics using cairo. This class represents a page / image file we are going to draw onto. :param img_format: The image format we are to produce. :type img_format: str :param output: The filename of the image file we are to produce, without a file type suffix :type output: str :param width: The width of the page, metres :type width: float :param height: The height of the page, metres :type height: float :param dots_per_inch: The dots per inch resolution to render this page :type dots_per_inch: float """ # PDF surfaces are always measured in points if img_format in ("pdf", "svg"): dots_per_inch = 72. self.format = img_format self.output = "{}.{}".format(output, img_format) self.dots_per_metre = dots_per_inch * 39.370079 self.width = int(width * self.dots_per_metre) self.height = int(height * self.dots_per_metre) if self.format == "pdf": self.surface = cairo.PDFSurface(self.output, self.width, self.height) elif self.format == "png": self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width, self.height) elif self.format == "svg": self.surface = cairo.SVGSurface(self.output, self.width, self.height) else: assert False, "Unknown image output format {}".format(self.format)
def create_rcontext(self, size, frame): """ Called when CairoCanvas needs a cairo context to draw on """ if self.format == 'pdf': surface = cairo.PDFSurface(self._output_file(frame), *size) elif self.format in ('ps', 'eps'): surface = cairo.PSSurface(self._output_file(frame), *size) elif self.format == 'svg': surface = cairo.SVGSurface(self._output_file(frame), *size) else: surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, *size) return cairo.Context(surface)
def text2svg(self): """Internally used function. Convert the text to SVG using Pango """ size = self.size * 10 line_spacing = self.line_spacing * 10 dir_name = config.get_dir("text_dir") disable_liga = self.disable_ligatures if not os.path.exists(dir_name): os.makedirs(dir_name) hash_name = self.text2hash() file_name = os.path.join(dir_name, hash_name) + ".svg" if os.path.exists(file_name): return file_name surface = cairocffi.SVGSurface(file_name, 600, 400) context = cairocffi.Context(surface) context.move_to(START_X, START_Y) settings = self.text2settings() offset_x = 0 last_line_num = 0 layout = pangocairocffi.create_layout(context) layout.set_width(pangocffi.units_from_double(600)) for setting in settings: family = setting.font style = self.str2style(setting.slant) weight = self.str2weight(setting.weight) text = self.text[setting.start : setting.end].replace("\n", " ") fontdesc = pangocffi.FontDescription() fontdesc.set_size(pangocffi.units_from_double(size)) if family: fontdesc.set_family(family) fontdesc.set_style(style) fontdesc.set_weight(weight) layout.set_font_description(fontdesc) if setting.line_num != last_line_num: offset_x = 0 last_line_num = setting.line_num context.move_to( START_X + offset_x, START_Y + line_spacing * setting.line_num ) pangocairocffi.update_layout(context, layout) if disable_liga: text = escape(text) layout.set_markup(f"<span font_features='liga=0'>{text}</span>") else: layout.set_text(text) logger.debug(f"Setting Text {text}") pangocairocffi.show_layout(context, layout) offset_x += pangocffi.units_to_double(layout.get_size()[0]) surface.finish() return file_name
def _make_surface(self, output_path, figure_format, figure_width, figure_height): """ Make the relevant Cairo surface and context with appropriate sizing. """ if figure_format == "PDF": surface = _cairo.PDFSurface(output_path, figure_width, figure_height) surface.set_metadata(_cairo.PDF_METADATA_CREATOR, f"eyekit {__version__}") elif figure_format == "EPS": surface = _cairo.PSSurface(output_path, figure_width, figure_height) surface.set_eps(True) elif figure_format == "SVG": surface = _cairo.SVGSurface(output_path, figure_width, figure_height) context = _cairo.Context(surface) return surface, context
def _get_text_dimensions(text: str, fontsize: int): try: import cairocffi as cairo except ImportError: return len(text) * fontsize, fontsize surface = cairo.SVGSurface('undefined65761354373731713.svg', 1280, 200) cairo_context = cairo.Context(surface) cairo_context.select_font_face('Arial', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) cairo_context.set_font_size(fontsize) _, _, width, height, _, _ = cairo_context.text_extents(text) # Don't forget to remove the undefined65761354373731713.svg file os.remove("undefined65761354373731713.svg") return width, height
def test_t2s() -> None: size = 1 temp_pango_text = Text("Helloworld", t2s={"world": ITALIC}) surface = cairocffi.SVGSurface(filename, WIDTH, HEIGTH) context = cairocffi.Context(surface) context.move_to(START_X, START_Y) layout = pangocairocffi.create_layout(context) layout.set_width(pangocffi.units_from_double(WIDTH)) fontdesc = pangocffi.FontDescription() fontdesc.set_size(pangocffi.units_from_double(size * 10)) layout.set_font_description(fontdesc) layout.set_markup( 'Hello<span style="italic">world</span>') # yay, pango markup pangocairocffi.show_layout(context, layout) surface.finish() assert compare_SVGObject_with_PangoText(temp_pango_text, filename)
def set_bounds(self, bounds, new_surface=False): origin_in_inch = (bounds[0][0], bounds[1][0]) size_in_inch = (abs(bounds[0][1] - bounds[0][0]), abs(bounds[1][1] - bounds[1][0])) size_in_pixels = self.scale_point(size_in_inch) self.origin_in_inch = origin_in_inch if self.origin_in_inch is None else self.origin_in_inch self.size_in_inch = size_in_inch if self.size_in_inch is None else self.size_in_inch self._xform_matrix = cairo.Matrix(xx=1.0, yy=-1.0, x0=-self.origin_in_pixels[0], y0=self.size_in_pixels[1]) if (self.surface is None) or new_surface: self.surface_buffer = tempfile.NamedTemporaryFile() self.surface = cairo.SVGSurface(self.surface_buffer, size_in_pixels[0], size_in_pixels[1]) self.output_ctx = cairo.Context(self.surface)
def new_render_layer(self, color=None, mirror=False): size_in_pixels = self.scale_point(self.size_in_inch) matrix = copy.copy(self._xform_matrix) layer = cairo.SVGSurface(None, size_in_pixels[0], size_in_pixels[1]) ctx = cairo.Context(layer) if self.invert: ctx.set_source_rgba(0.0, 0.0, 0.0, 1.0) ctx.set_operator(cairo.OPERATOR_OVER) ctx.paint() if mirror: matrix.xx = -1.0 matrix.x0 = self.origin_in_pixels[0] + self.size_in_pixels[0] self.ctx = ctx self.ctx.set_matrix(matrix) self.active_layer = layer self.active_matrix = matrix
def run(fn, roll=-3, pitch=40): surface = cairo.SVGSurface(fn + ".svg", max_x, max_y) if roll > 60: roll = 60 elif roll < -60: roll = -60 if pitch > 30: pitch = 30 elif pitch < -30: pitch = -30 cr = cairo.Context(surface) with cr: main(cr, roll, pitch) surface.write_to_png(fn + ".png")
def test_rtl_text_to_svgobject() -> None: """Checks number of submobjects generated when directly called using ``SVGMobject``""" size = 1 text = RTL_TEXT.replace("\n", "") temp_pango_text = Text(text, size=1) surface = cairocffi.SVGSurface(filename, WIDTH, HEIGTH) context = cairocffi.Context(surface) context.move_to(START_X, START_Y) layout = pangocairocffi.create_layout(context) layout.set_width(pangocffi.units_from_double(WIDTH)) fontdesc = pangocffi.FontDescription() fontdesc.set_size(pangocffi.units_from_double(size * 10)) layout.set_font_description(fontdesc) layout.set_text(text) pangocairocffi.show_layout(context, layout) surface.finish() assert compare_SVGObject_with_PangoText(temp_pango_text, filename)