def render_text(self, text,file_type='png', width=0, height=0,color="Black"): surface = None width=int(width) height=int(height) text= text.decode("utf-8") filename = str(uuid.uuid1())[0:5]+"."+file_type outputfile = os.path.join(self.tmp_folder, filename ) if file_type == 'png': surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(width), int(height)) if file_type == 'svg': surface = cairo.SVGSurface(outputfile,int(width),int(height)) if file_type == 'pdf': surface = cairo.PDFSurface(outputfile,int(width),int(height)) context = cairo.Context(surface) try: text = hyphenator.getInstance().hyphenate(text,u'\u00AD') except: print("error while hyphenating. Proceeding without Hyphenation") width = int(width) font_size = 10 left_margin = 10 top_margin = 10 position_x = left_margin position_y = top_margin rgba = get_color(color) context.set_source_rgba (rgba.red,rgba.green,rgba.blue,rgba.alpha) pc = pangocairo.CairoContext(context) paragraph_layout = pc.create_layout() paragraph_font_description = pango.FontDescription() paragraph_font_description.set_family("Serif") paragraph_font_description.set_size((int)(int(font_size) * pango.SCALE)) paragraph_layout.set_font_description(paragraph_font_description) if width>0: paragraph_layout.set_width((int)((width-2*left_margin) * pango.SCALE)) paragraph_layout.set_justify(True) paragraph_layout.set_text(text+"\n") context.move_to(position_x, position_y) pango_layout_iter = paragraph_layout.get_iter(); line_width = 0 while not pango_layout_iter.at_last_line(): first_line = True context.move_to(position_x, position_y) while not pango_layout_iter.at_last_line() : ink_rect, logical_rect = pango_layout_iter.get_line_extents() line = pango_layout_iter.get_line_readonly() has_next_line=pango_layout_iter.next_line() # Decrease paragraph spacing if ink_rect[2] == 0 : #It is para break dy = font_size / 2 position_y += dy if not first_line: self.context.rel_move_to(0, dy) else: xstart = 1.0 * logical_rect[0] / pango.SCALE context.rel_move_to(xstart, 0) if width >0 and height > 0 : pc.show_layout_line( line) line_height = (int)(logical_rect[3] / pango.SCALE) line_width = (int)(logical_rect[2] / pango.SCALE) context.rel_move_to(-xstart, line_height ) position_y += line_height first_line = False if width==0 or height==0: if width==0: width = line_width if height==0: height = position_y return self.render_text(text,file_type, width + 2.5*left_margin, height,color) if file_type == 'png': surface.write_to_png(outputfile) else: context.show_page() return "modules/render/tmp/"+filename
knownCommands["c"] = circle knownCommands["translate"] = translate knownCommands["stroke"] = stroke # knownCommands["rotate"] = rotate def parseCommand(ctx, cmd, values): global knownCommands if cmd in knownCommands: knownCommands[cmd](ctx, values) else: print("skipping task " + cmd + ", ".join([str(x) for x in values])) f = open(sys.argv[1], 'r') filename = sys.argv[1] + ".svg" surface = cairo.SVGSurface(filename, 8.5 * 300, 11 * 300) context = cairo.Context(surface) for line in f: ll = line.split(" ") cmd = ll[0] vals = [float(x) for x in ll[1:]] parseCommand(context, cmd, vals) context.stroke() symlink_force(filename, "latest.svg")
@property def start(self): return (radius * math.cos(self.start_theta)) + cx, (radius * math.sin(self.start_theta)) + cy @property def end(self): return (radius * math.cos(self.end_theta)) + cx, (radius * math.sin(self.end_theta)) + cy # mults = arange(2, n_lines // 2, .002) # for n in mults: # hue_start += .001 n = multiplier lines = [Line(i, angle_step * i - math.pi, angle_step * ((i * n) % n_lines) - math.pi) for i in range(n_lines)] with cairo.SVGSurface('logo.svg', width, height) as surface: # with cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) as surface: ctx = cairo.Context(surface) ctx.set_line_width(1) # ctx.set_font_size(8) # r1 = cairo.RadialGradient(cx, cy, 50, cx, cy, radius) # r1.add_color_stop_rgb(1, .1, .1, .1) # r1.add_color_stop_rgb(0, .05, .05, .05) # ctx.set_source(r1) # ctx.rectangle(0, 0, width, height) # ctx.fill() for line in lines: # ctx.set_source_rgba(0, 0, 0, 1) # radius += 8 # ctx.move_to(*line.start) # ctx.show_text(str(line.place or n_lines))
message('rendering: %s -> %s...' % (pname, outfilename)) view = View(diagram.canvas) view.painter = ItemPainter() tmpsurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0) tmpcr = cairo.Context(tmpsurface) view.update_bounding_box(tmpcr) tmpcr.show_page() tmpsurface.flush() w, h = view.bounding_box.width, view.bounding_box.height if options.format == 'pdf': surface = cairo.PDFSurface(outfilename, w, h) elif options.format == 'svg': surface = cairo.SVGSurface(outfilename, w, h) elif options.format == 'png': surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(w+1), int(h+1)) else: assert False, 'unknown format %s' % options.format cr = cairo.Context(surface) view.matrix.translate(-view.bounding_box.x, -view.bounding_box.y) view.paint(cr) cr.show_page() if options.format == 'png': surface.write_to_png(outfilename) surface.flush() surface.finish()
InputMotif.close() #Create three lists pertaining to the colors that will be used to represent each individual motif red = [] green = [] blue = [] for motif in motifs: red.append(random.randint(0, 100) / 100) green.append(random.randint(0, 100) / 100) blue.append(random.randint(0, 100) / 100) ############################ #Create our base x and y draw values and initiate our cairo surface by the calculated values x = 25 #This can be used to tune how far fromt he margin we wish to start our images/writing y = 0 surface = cairo.SVGSurface(FileName + ".svg", entrylength + (x * 2), (nlines * 50) + 50) context = cairo.Context(surface) context.set_font_size(8) #Draw a legend of what each motif color means n = 25 #Decides how far down the y acis we wish to start our legend for motif, r, g, b in zip(motifs, red, green, blue): if n == 25: n = draw_legend(r, g, b, n, motif) else: n = draw_legend(r, g, b, n, motif) ############################ #The way we will draw the exons will be to first draw an entire line to signify the whole gene (introns) then for each position in which #an upper case character was found (exon), we will draw a vertical line. Then we will look at the motifs and draw different #colored horizontal lines through each respective site
def render(options): # create view if (options.view): columns = options.viewcolumns.split(',') if (options.extracolumns): columns += options.extracolumns.split(',') create_views(options.dsn, options.dbprefix, options.viewprefix, options.viewhstore, columns, options.date) # create map m = mapnik.Map(options.size[0], options.size[1]) # load style mapnik.load_map(m, options.style) # create projection object prj = mapnik.Projection( "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ) #c0 = prj.forward(Coord(bbox[0],bbox[1])) #c1 = prj.forward(Coord(bbox[2],bbox[3])) #e = Box2d(c0.x,c0.y,c1.x,c1.y) # map bounds if hasattr(mapnik, 'Box2d'): bbox = mapnik.Box2d(*options.bbox) else: bbox = mapnik.Envelope(*options.bbox) # project bounds to map projection e = mapnik.forward_(bbox, prj) # zoom map to bounding box m.zoom_to_box(e) options.file = options.file + "." + options.type if (options.type in ("png", "jpeg")): s = mapnik.Image(options.size[0], options.size[1]) elif cairo_exists and type == "svg": s = cairo.SVGSurface(options.file, options.size[0], options.size[1]) elif cairo_exists and type == "pdf": s = cairo.PDFSurface(options.file, options.size[0], options.size[1]) elif cairo_exists and type == "ps": s = cairo.PSSurface(options.file, options.size[0], options.size[1]) else: print "invalid image type" print parser.print_help() sys.exit(1) mapnik.render(m, s) if isinstance(s, mapnik.Image): view = s.view(0, 0, options.size[0], options.size[1]) view.save(options.file, options.type) elif isinstance(s, cairo.Surface): s.finish() if (options.view): drop_views(options.dsn, options.viewprefix)
def setup_svg(self): self.surface = cairo.SVGSurface(self.fullpath, self.width, self.height) return cairo.Context(self.surface)
sumY = sumY + sums[1] sumX = sumX / len(magnets) sumY = sumY / len(magnets) p.resetForce() p.setForce(sumX, sumY) p.update() p.edges() if t % 8 == 0: p.draw(context) p.setLastPos() # Call the main function if __name__ == '__main__': if fileFormat == 'PNG': surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = cairo.Context(surface) main() filename = uuid.uuid4().hex[:8] surface.write_to_png('Images/Magnetic_Flow/' + str(filename) + '.png') elif fileFormat == 'SVG': filename = uuid.uuid4().hex[:8] surface = cairo.SVGSurface( 'Images/Magnetic_Flow/0-svg/' + str(filename) + '.svg', width, height) context = cairo.Context(surface) main() surface.finish()
options.ozi.write(prepare_ozi(bbox, size[0], size[1], options.output)) if options.wld: options.wld.write(prepare_wld(bbox, size[0], size[1])) # export image m.aspect_fix_mode = mapnik.aspect_fix_mode.GROW_BBOX; m.resize(size[0], size[1]) m.zoom_to_box(bbox) outfile = options.output if options.output == '-': outfile = tempfile.TemporaryFile(mode='w+b') if need_cairo: if HAS_CAIRO: surface = cairo.SVGSurface(outfile, size[0], size[1]) if fmt == 'svg' else cairo.PDFSurface(outfile, size[0], size[1]) mapnik.render(m, surface, scale_factor, 0, 0) surface.finish() else: mapnik.render_to_file(m, outfile, fmt) else: if options.tiles == 1: im = mapnik.Image(size[0], size[1]) mapnik.render(m, im, scale_factor) im.save(outfile, fmt) else: # we cannot make mapnik calculate scale for us, so fixing aspect ratio outselves rdiff = (bbox.maxx-bbox.minx) / (bbox.maxy-bbox.miny) - size[0] / size[1] if rdiff > 0: bbox.height((bbox.maxx - bbox.minx) * size[1] / size[0]) elif rdiff < 0:
motif_pos_dict[(GCAUG_start_pos, GCAUG_end_pos)] = GCAUG_motif_key for catag in catag_rgx.finditer(line): #print(catag.start(), catag.end(), catag.group()) catag_start_pos = catag.start() catag_end_pos = catag.end() catag_motif_key = catag.group() motif_pos_dict[(catag_start_pos, catag_end_pos)] = catag_motif_key return (motif_pos_dict) m_list = parse_motif_file(m) parse_motif_file(m) surface = cairo.SVGSurface("motif_plot.svg", 800, 500) context = cairo.Context(surface) context.move_to(50, 10) context.show_text("Motif Legend:") context.set_line_width(20) context.set_source_rgb(1, .1, .1) context.move_to(50, 25) context.line_to(100, 25) context.show_text(m_list[0]) context.stroke() context = cairo.Context(surface) context.set_line_width(20) context.set_source_rgb(.32, .60, 0.1) context.move_to(50, 50) context.line_to(100, 50) context.show_text(m_list[1])
for w in walkers: if walkers[i].id != w.id and walkers[ i - 1].id != w.id and walkers[i].connect != w.id: if walkers[i].intersect(w.p0, w.p1) or walkers[i].edges(): stopDrawing = True break if stopDrawing: break walkers[i].draw(context) # Call the main function and save an image if __name__ == '__main__': if fileFormat == 'PNG': surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) context = cairo.Context(surface) main() fileName = uuid.uuid4().hex[:8] surface.write_to_png("Images/Line_Walker/" + str(fileName) + ".png") elif fileFormat == 'SVG': fileName = uuid.uuid4().hex[:8] surface = cairo.SVGSurface( "Images/Line_Walker/0-svg/" + str(fileName) + ".svg", width, height) context = cairo.Context(surface) main() context.finish()
# Clear path to parent. pc = c.parent if pc != None and pc != True: p = self.cells[pc] c.remove_wall(pc) p.remove_wall(cc) # Add the neighbors to the open list. neighbors = [n for n in c.neighbors if not self.cells[n].visited()] for n in neighbors: self.cells[n].visit(cc) stack += neighbors # Shuffle for next round. random.shuffle(stack) # Make the maze. maze = Maze(20) maze.drill() # Render the maze. surface = cairo.SVGSurface("maze.svg", dim, dim) ctx = cairo.Context(surface) ctx.set_tolerance(0.01) ctx.set_line_width(0.5) ctx.set_source_rgb(0, 0, 0) maze.render(ctx) ctx.stroke()
r'([A-Z]+)', str(sequence)).span(1)[0] #Records start and end position of exon exon_end = re.search(r'([A-Z]+)', str(sequence)).span(1)[1] for elem in motif_dict: motif_mark[elem] = [] for match in re.finditer( elem, str(sequence).upper()): #Again records motifs motif_mark[elem].append(match.start()) seq_motif[header] = motif_mark seq_exon[header] = (exon_start, exon_end) #The two lines above record the motifs and exons for this specific sequence in dictionaries where the keys are the header of the sequence and the values are the motif start #position dictionary and exon start and end positions. surface = cairo.SVGSurface( "plot.svg", longest_seq + 200, 200 * len(sequence_dict)) #establishes the surface for plotting context = cairo.Context(surface) context.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) start_height = 25 for seq in sequence_dict: context.set_source_rgb(0, 0, 0) context.set_line_width(1) context.move_to(50, start_height) context.set_font_size(20) context.show_text(seq) start_height += 50 context.move_to(50, start_height) context.line_to(len(sequence_dict[seq]) + 50, start_height) context.stroke()
#by default iupac_conversions dictionary creates DNA motif sequences new_dna_motif.append("".join(i)) #replace every thymine with uracil for the RNA motif sequences new_rna_motif.append("".join(i).replace("T", "U")) #add all possible motif sequences into respective dictionaries DNA[motif] = new_dna_motif RNA[motif] = new_rna_motif #return dictionaries return DNA, RNA DNA, RNA = motif_maker(motif_file) #for each fasta file run the program on it for file in fasta_files: #extract file name for use in naming plot figname = re.findall('(.*)\.fa', file)[0] + ".svg" #create a pycairo surface surface = cairo.SVGSurface(figname, 1000, 150 * (number_of_genes + 1)) #create context on the pycairo surface context = cairo.Context(surface) geneGroups = parser(file, context) legend = Legend(DNA) legend.draw(context) context.stroke() surface.finish()
self.inputs = inputs self.x = None self.y = None for t in range(len(tiers)): for pm, _, inputs in tiers[t]: tid = pm["typeID"] mat = Mat(t, tid, pm["typeName"], inputs) mats[tid] = mat mat_tiers[t].append(mat.tid) # Set up Cairo for drawing. Origin is in upper-left corner. height = SIDE width = round(ASPECT * SIDE) surface = cairo.SVGSurface("pi-chart.svg", width, height) ctx = cairo.Context(surface) ctx.select_font_face("sans-serif", cairo.FontSlant.NORMAL, cairo.FontWeight.BOLD) font_face = ctx.get_font_face() ctx.set_line_width(1.2) # Set up column widths and heights. col_margin = 0.05 * width row_margin = 0.05 * height gutter_width = 0.15 * width ncols = len(mat_tiers) row_maxwidth = [None] * ncols nrow = [None] * ncols font_height = 0.0 font_ascent = 0.0
def _render_one(self, config, tmpdir, renderer_cls, output_format, output_filename, osm_date, file_prefix): LOG.debug('Rendering to %s format...' % output_format.upper()) dpi = layoutlib.commons.PT_PER_INCH config.output_format = output_format renderer = renderer_cls(self._db, config, tmpdir, dpi, file_prefix) if output_format == 'png': try: dpi = int(self._parser.get('rendering', 'png_dpi')) except configparser.NoOptionError: dpi = OCitySMap.DEFAULT_RENDERING_PNG_DPI w_px = int( layoutlib.commons.convert_mm_to_dots(config.paper_width_mm, dpi)) h_px = int( layoutlib.commons.convert_mm_to_dots(config.paper_height_mm, dpi)) if w_px > 25000 or h_px > 25000: LOG.warning( "%d DPI to high for this paper size, using 72dpi instead" % dpi) dpi = layoutlib.commons.PT_PER_INCH # as the dpi value may have changed we need to re-create the renderer renderer = renderer_cls(self._db, config, tmpdir, dpi, file_prefix) # As strange as it may seem, we HAVE to use a vector # device here and not a raster device such as # ImageSurface. Because, for some reason, with # ImageSurface, the font metrics would NOT match those # pre-computed by renderer_cls.__init__() and used to # layout the whole page w_px = int( layoutlib.commons.convert_pt_to_dots(renderer.paper_width_pt, dpi)) h_px = int( layoutlib.commons.convert_pt_to_dots(renderer.paper_height_pt, dpi)) LOG.debug("Rendering PNG into %dpx x %dpx area at %ddpi ..." % (w_px, h_px, dpi)) surface = cairo.PDFSurface(None, w_px, h_px) elif output_format == 'svg': surface = cairo.SVGSurface(output_filename, renderer.paper_width_pt, renderer.paper_height_pt) surface.restrict_to_version(cairo.SVGVersion.VERSION_1_2) elif output_format == 'svgz': surface = cairo.SVGSurface(gzip.GzipFile(output_filename, 'wb'), renderer.paper_width_pt, renderer.paper_height_pt) surface.restrict_to_version(cairo.SVGVersion.VERSION_1_2) elif output_format == 'pdf': surface = cairo.PDFSurface(output_filename, renderer.paper_width_pt, renderer.paper_height_pt) surface.restrict_to_version(cairo.PDFVersion.VERSION_1_5) surface.set_metadata(cairo.PDFMetadata.CREATOR, 'MyOSMatic <https://print.get-map.org/>') surface.set_metadata(cairo.PDFMetadata.TITLE, config.title) surface.set_metadata( cairo.PDFMetadata.AUTHOR, "Copyright © 2018 MapOSMatic/OCitySMap developers. \n" + "Map data © 2018 OpenStreetMap contributors (see http://osm.org/copyright)" ) surface.set_metadata( cairo.PDFMetadata.SUBJECT, renderer.description) # TODO add style annotations here surface.set_metadata(cairo.PDFMetadata.KEYWORDS, "OpenStreetMap, MapOSMatic, OCitysMap") elif output_format == 'ps': surface = cairo.PSSurface(output_filename, renderer.paper_width_pt, renderer.paper_height_pt) elif output_format == 'ps.gz': surface = cairo.PSSurface(gzip.GzipFile(output_filename, 'wb'), renderer.paper_width_pt, renderer.paper_height_pt) elif output_format == 'csv': # We don't render maps into CSV. return else: raise ValueError( \ 'Unsupported output format: %s!' % output_format.upper()) renderer.render(surface, dpi, osm_date) LOG.debug('Writing %s...' % output_filename) if output_format == 'png': surface.write_to_png(output_filename) surface.finish()
def draw_a_gene(gene_objects, gene_nums, margin, motif_ext, motif_colors, svg_name): # initialize surface surface = cairo.SVGSurface(svg_name, 1000, 1000) context = cairo.Context(surface) # make a figure title context.set_source_rgb(0, 0, 0) context.set_font_size(30) context.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) context.move_to(margin, 40) context.show_text("Motif Finder Results") context.stroke() # iterate through all genes for gene_num,gene_obj in zip(gene_nums, gene_objects): # draw gene title context.set_source_rgb(0, 0, 0) context.set_font_size(15) context.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) context.move_to(margin, gene_num-25) context.show_text(gene_obj.fasta_header) context.stroke() # draw gene length context.set_line_width(3) context.move_to(margin, gene_num) context.line_to(gene_obj.end, gene_num) context.stroke() # draw exons context.set_line_width(15) for exon in gene_obj.exons: e0 = exon[0] e1 = exon[1] context.move_to(e0 + margin, gene_num) context.line_to(e1 + margin, gene_num) context.stroke() # draw motifs #context.scale (10000, 10000) for motif in gene_obj.motif_coordinates.keys(): #context.set_source_rgb(52, 235, 207) red = motif_colors[motif][0] green = motif_colors[motif][1] blue = motif_colors[motif][2] for coord in gene_obj.motif_coordinates[motif]: # coord = (start, stop) m0 = coord[0] m1 = coord[1] # draw line at motif context.set_line_width(15) context.set_source_rgba(red, green, blue, .5) context.move_to(m0+margin, gene_num) context.line_to(m1+margin, gene_num) context.stroke() # make motif legend start_legend = max(gene_nums) + 40 for motif in motif_colors.keys(): # get rgb colors red = motif_colors[motif][0] green = motif_colors[motif][1] blue = motif_colors[motif][2] #draw label context.set_source_rgb(0, 0, 0) context.set_font_size(15) context.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) context.move_to(margin+60, start_legend+3) context.show_text(motif) context.stroke() # draw line color # draw line at motif context.set_line_width(10) context.set_source_rgb(red, green, blue) context.move_to(margin, start_legend) context.line_to(margin + 50, start_legend) context.stroke() start_legend += 20 surface.finish()
def drawing(gene_objects, output_name, pallete, sequence_file, motif_file, motifs): ''' All functions for the pycairo graphic Takes in each of the gene objects (with exons and motifs stored), the name of the file to write to, the color pallete, the original motifs in IUPAC form, and the names of the input files. Outputs a SVG. Each fasta sequence from the input file gets its own drawing. The drawings are depicted as the same size, but exon and motif bounds are scaled in size relative to the length of the gene. Each gene drawing shows the exons as grey boxes and introns as straight dark lines. Motifs are represented by colored boxes spanning the window which matched the motif. A key is provided at the bottom to associate motifs with their color. The original file names are written to the output for record keeping. ''' #determine how many genes need to be represented gene_count = len(gene_objects) + 1 #height for each gene base_height = 100 #dimensions of total output, scaled for number of genes width, height = 600, base_height * (gene_count + 1) #name of output filename = output_name + ".svg" #leaving whitespace for ease of viewing left_indent = width * .1 #width of gene in visual, relative to width of whole image gene_width = width * .8 with cairo.SVGSurface(filename, width, height) as surface: #create visual object context = cairo.Context(surface) #which gene were on, used for scaling height coordinates gene_count = 1 for gene in gene_objects: #make a straight line for each gene context.set_source_rgb(0, 0, 0) x1, y1 = width * .1, base_height * .5 + base_height * gene_count x2, y2 = width * .9, base_height * .5 + base_height * gene_count context.set_line_width(1) context.move_to(x1, y1) context.line_to(x2, y2) #add the name of each gene/fasta entry above the visual x3, y3 = width * .09, base_height * .1 + base_height * gene_count context.move_to(x3, y3) gene_name = gene + " {} BP".format( len(gene_objects[gene].sequence)) context.show_text(gene_name) context.stroke() #find length of gene to scale motifs and exons accordingly gene_length = len(gene_objects[gene].sequence) #add the exon as a rectangle for exon in gene_objects[gene].exons: exon_start, exon_stop = exon #scale the start position for the graphic exon_x1 = (exon_start / gene_length) * gene_width + left_indent exon_y1 = base_height * 0.3 + base_height * gene_count exon_height = base_height * 0.4 exon_width = (exon_stop - exon_start) / gene_length * gene_width #make a grey box that is wider than the intron lines context.rectangle(exon_x1, exon_y1, exon_width, exon_height) context.set_source_rgb(.6, .6, .6) context.fill() #now iterating through each motif found in this sequence for motif in gene_objects[gene].motifs: #grabbing BP coordinates for where the motifs matched the sequence (often more than one) for window in gene_objects[gene].motifs[motif]: #output the motifs as boxes re_x1 = (((window[0] / gene_length) * gene_width) + left_indent) re_width = (window[1] - window[0]) / gene_length * gene_width re_height = base_height * .2 context.rectangle( re_x1, base_height * .4 + base_height * gene_count, re_width, re_height) #uses the same color for same motifs r, g, b, a = pallete[motif] context.set_source_rgba(r, g, b, a) context.fill() gene_count += 1 #adding figure title context.move_to(width * 0.1, base_height * 0.5) context.set_source_rgb(0, 0, 0) context.set_font_size(10.0) context.show_text( "Identifying motifs described in the file '{}' found in the file '{}'" .format(motif_file, sequence_file)) context.move_to(width * 0.1, base_height * 0.7) context.set_source_rgb(0, 0, 0) context.set_font_size(7.0) context.show_text( "Grey boxes represent exons, and colored boxes represent motifs. See motif legend below." ) #adding the motif legend legend_x, legend_y = left_indent, base_height * 0.2 + base_height * gene_count legend_horiz_spacing = width * 0.2 legend_vert_spacing = base_height * 0.1 context.move_to(legend_x, legend_y - legend_vert_spacing) context.set_font_size(10) context.show_text("Motif legend") motif_count = 0 line = 0 for motif in motifs: #wrapping so 4 motifs appear in each line if motif_count % 4 == 0: line += 1 x1, y1 = (legend_x + (motif_count % 4) * legend_horiz_spacing), ( legend_y + legend_vert_spacing * line) context.move_to(x1, y1) #cute lil boxes context.rectangle(x1, y1, base_height * 0.05, base_height * 0.05) r, g, b, a = pallete[motifs[motif]] context.set_source_rgba(r, g, b, a) context.fill() #write the original motif x1, y1 = x1 + base_height * 0.07, y1 + base_height * 0.07 context.move_to(x1, y1) context.set_source_rgb(0, 0, 0) context.show_text(motifs[motif].upper()) motif_count += 1
#In cm import cairo width = WIDTH = height = HEIGHT = 5 PIXEL_SCALE = 100 #400 px width and height #width, height = width_in_points, height_in_points with cairo.SVGSurface("m_logo.svg", WIDTH * PIXEL_SCALE, HEIGHT * PIXEL_SCALE) as surface: ctx = cairo.Context(surface) ctx.scale(PIXEL_SCALE, PIXEL_SCALE) #scaling #making a M #ctx.set_line_width(1) ctx.set_line_width(0.1) ctx.move_to(0, 2.5) ctx.line_to(2.5, 0) ctx.line_to(2.5, 2.5) ctx.line_to(5, 2.5) ctx.line_to(2.5, 5) ctx.set_source_rgb(0.8, 0.5, 0.7) #color #ctx.set_line_width(0.1) ctx.stroke() surface.write_to_png('m_logo.png') import os os.startfile("m_logo.svg")
import cairo with cairo.SVGSurface("pycairo_generated.svg", 200, 200) as surface: context = cairo.Context(surface) x, y, x1, y1 = 0.1, 0.5, 0.4, 0.9 x2, y2, x3, y3 = 0.6, 0.1, 0.9, 0.5 context.scale(200, 200) context.set_line_width(0.04) context.move_to(x, y) context.curve_to(x1, y1, x2, y2, x3, y3) context.stroke() context.set_source_rgba(1, 0.2, 0.2, 0.6) context.set_line_width(0.02) context.move_to(x, y) context.line_to(x1, y1) context.move_to(x2, y2) context.line_to(x3, y3) context.stroke()
import cairo with cairo.SVGSurface("exemplo.svg", 400, 400) as surface: c = cairo.Context(surface) c.scale(400, 400) c.set_line_width(1) c.move_to(1, 1) c.line_to(0.5, 0.5) c.move_to(2, 2.5) c.line_to(-0.5, -0.5) c.set_source_rgb(0.03, 0, 1) c.stroke()
print("Minimal distance after filtering:", min(distances)) nodes = list(set([val for sublist in edges for val in sublist])) ######## EDGES FILTERED ######## drawTree(edges=edges, nodes=leafs, title="I") nodes.sort(key=lambda node: node.norm()) leafs = [] for N in nodes: neighbours = [edge for edge in edges if N in edge] if len(neighbours) == 1: # If node is a leaf leafs.append(N) surface = cairo.SVGSurface("after.svg", WIDTH, HEIGHT) surface.set_document_unit(cairo.SVG_UNIT_MM) ctx = cairo.Context(surface) # ctx.set_source_rgb(0.2, 0.2, 0.2) # ctx.rectangle(0, 0, WIDTH, HEIGHT) # ctx.fill() # ctx.set_source_rgb(1, 1, 1) # ctx.set_line_width(1) img = np.ones((HEIGHT, WIDTH, 3)) * 0.1 nLeafsDrawn = 0 for NODE in nodes:
def run(options): dim_mm = None scale = None size = None bbox = None rotate = not options.norotate if (options.ozi and options.projection.lower() != 'epsg:3857' and options.projection != EPSG_3857): raise Exception( 'Ozi map file output is only supported for Web Mercator (EPSG:3857). ' + 'Please remove --projection.') if options.url: parse_url(options.url, options) # format should not be empty if options.fmt: fmt = options.fmt.lower() elif '.' in options.output: fmt = options.output.split('.')[-1].lower() else: fmt = 'png256' need_cairo = fmt in ['svg', 'pdf'] # output projection if options.projection.isdigit(): proj_target = mapnik.Projection('+init=epsg:{}'.format( options.projection)) else: proj_target = mapnik.Projection(options.projection) transform = mapnik.ProjTransform(proj_lonlat, proj_target) # get image size in millimeters if options.paper: portrait = False if options.paper[0] == '-': portrait = True rotate = False options.paper = options.paper[1:] elif options.paper[0] == '+': rotate = False options.paper = options.paper[1:] else: rotate = True dim_mm = get_paper_size(options.paper.lower()) if not dim_mm: raise Exception('Incorrect paper format: ' + options.paper) if portrait: dim_mm = [dim_mm[1], dim_mm[0]] elif options.size: dim_mm = options.size if dim_mm and options.margin: dim_mm[0] = max(0, dim_mm[0] - options.margin * 2) dim_mm[1] = max(0, dim_mm[1] - options.margin * 2) # ppi and scale factor are the same thing if options.ppi: ppmm = options.ppi / 25.4 scale_factor = options.ppi / 90.7 else: scale_factor = options.factor ppmm = 90.7 / 25.4 * scale_factor # svg / pdf can be scaled only in cairo mode if scale_factor != 1 and need_cairo and not HAS_CAIRO: logging.error('Warning: install pycairo for using --factor or --ppi') scale_factor = 1 ppmm = 90.7 / 25.4 # convert physical size to pixels if options.size_px: size = options.size_px elif dim_mm: size = [int(round(dim_mm[0] * ppmm)), int(round(dim_mm[1] * ppmm))] if size and size[0] + size[1] <= 0: raise Exception('Both dimensions are less or equal to zero') if options.bbox: bbox = options.bbox # scale can be specified with zoom or with 1:NNN scale fix_scale = False if options.zoom: scale = 2 * 3.14159 * 6378137 / 2**(options.zoom + 8) / scale_factor elif options.scale: scale = options.scale * 0.00028 / scale_factor # Now we have to divide by cos(lat), but we might not know latitude at this point # TODO: division should only happen for EPSG:3857 or not at all if options.center: scale = scale / math.cos(math.radians(options.center[1])) elif options.bbox: scale = scale / math.cos( math.radians((options.bbox[3] + options.bbox[1]) / 2)) else: fix_scale = True # all calculations are in EPSG:3857 projection (it's easier) if bbox: bbox = transform.forward(mapnik.Box2d(*bbox)) bbox_web_merc = transform_lonlat_webmerc.forward( mapnik.Box2d(*(options.bbox))) if scale: scale = correct_scale(bbox, scale, bbox_web_merc, bbox) # calculate bbox through center, zoom and target size if not bbox and options.center and size and size[0] > 0 and size[ 1] > 0 and scale: # We don't know over which latitude range the bounding box spans, so we # first do everything in Web Mercator. center = transform_lonlat_webmerc.forward( mapnik.Coord(*options.center)) w = size[0] * scale / 2 h = size[1] * scale / 2 bbox_web_merc = mapnik.Box2d(center.x - w, center.y - h, center.x + w, center.y + h) bbox = transform_lonlat_webmerc.backward(bbox_web_merc) bbox = transform.forward(bbox) # now correct the scale scale = correct_scale(bbox, scale, bbox_web_merc, bbox) center = transform.forward(mapnik.Coord(*options.center)) w = size[0] * scale / 2 h = size[1] * scale / 2 bbox = mapnik.Box2d(center.x - w, center.y - h, center.x + w, center.y + h) # reading style xml into memory for preprocessing if options.style == '-': style_xml = sys.stdin.read() style_path = '' else: with codecs.open(options.style, 'r', 'utf-8') as style_file: style_xml = style_file.read() style_path = os.path.dirname(options.style) if options.base: style_path = options.base if options.vars: style_xml = xml_vars(style_xml, options.vars) if options.layers or options.add_layers: style_xml = reenable_layers( style_xml, parse_layers_string(options.layers) + parse_layers_string(options.add_layers)) # for layer processing we need to create the Map object # ----- BEGIN PRINTMAPS ----- # m = mapnik.Map(100, 100) # temporary size, will be changed before output m = mapnik.Map(size[0], size[1]) # ----- END PRINTMAPS ----- mapnik.load_map_from_string(m, style_xml.encode("utf-8"), False, style_path) m.srs = proj_target.params() # register non-standard fonts if options.fonts: for f in options.fonts: add_fonts(f) # get bbox from layer extents if options.fit: bbox = layer_bbox(m, options.fit.split(','), proj_target, bbox) # here's where we can fix scale, no new bboxes below if bbox and fix_scale: scale = scale / math.cos( math.radians(transform.backward(bbox.center()).y)) bbox_web_merc = transform_lonlat_webmerc.forward( transform.backward(bbox)) if scale: scale = correct_scale(bbox, scale, bbox_web_merc, bbox) # expand bbox with padding in mm if bbox and options.padding and (scale or size): if scale: tscale = scale else: tscale = min((bbox.maxx - bbox.minx) / max(size[0], 0.01), (bbox.maxy - bbox.miny) / max(size[1], 0.01)) bbox.pad(options.padding * ppmm * tscale) # bbox should be specified by this point if not bbox: raise Exception('Bounding box was not specified in any way') # rotate image to fit bbox better if rotate and size: portrait = bbox.maxy - bbox.miny > bbox.maxx - bbox.minx # take into consideration zero values, which mean they should be calculated from bbox if (size[0] == 0 or size[0] > size[1]) and portrait: size = [size[1], size[0]] # calculate pixel size from bbox and scale if not size: if scale: size = [ int(round(abs(bbox.maxx - bbox.minx) / scale)), int(round(abs(bbox.maxy - bbox.miny) / scale)) ] else: raise Exception( 'Image dimensions or scale were not specified in any way') elif size[0] == 0: size[0] = int( round(size[1] * (bbox.maxx - bbox.minx) / (bbox.maxy - bbox.miny))) elif size[1] == 0: size[1] = int( round(size[0] / (bbox.maxx - bbox.minx) * (bbox.maxy - bbox.miny))) if options.output == '-' or (need_cairo and options.tiles > 1): options.tiles = 1 # ----- BEGIN PRINTMAPS ----- # if max(size[0], size[1]) / options.tiles > 16384: # raise Exception('Image size exceeds mapnik limit ({} > {}), use --tiles'.format( # max(size[0], size[1]) / options.tiles, 16384)) # ----- END PRINTMAPS ----- # add / remove some layers if options.layers: filter_layers(m, parse_layers_string(options.layers)) if options.add_layers or options.hide_layers: select_layers(m, parse_layers_string(options.add_layers), parse_layers_string(options.hide_layers)) # ----- BEGIN PRINTMAPS ----- # logging.debug('scale=%s', scale) # logging.debug('scale_factor=%s', scale_factor) # logging.debug('size=%s,%s', size[0], size[1]) # logging.debug('bbox=%s', bbox) # logging.debug('bbox_wgs84=%s', transform.backward(bbox) if bbox else None) # logging.debug('layers=%s', ','.join([l.name for l in m.layers if l.active])) print('scale={}'.format(scale)) print('scale_factor={}'.format(scale_factor)) print('size={},{}'.format(size[0], size[1])) print('bbox={}'.format(bbox)) print('bbox_wgs84={}'.format(transform.backward(bbox) if bbox else None)) print('layers=' + ','.join([l.name for l in m.layers if l.active])) # ----- END PRINTMAPS ----- # ----- BEGIN PRINTMAPS ----- if options.info: quit() # ----- END PRINTMAPS ----- # generate metadata if options.ozi: options.ozi.write( prepare_ozi(bbox, size[0], size[1], options.output, transform)) if options.wld: options.wld.write(prepare_wld(bbox, size[0], size[1])) # export image m.aspect_fix_mode = mapnik.aspect_fix_mode.GROW_BBOX # ----- BEGIN PRINTMAPS ----- # m.resize(size[0], size[1]) # ----- END PRINTMAPS ----- m.zoom_to_box(bbox) outfile = options.output if options.output == '-': outfile = tempfile.TemporaryFile(mode='w+b') if need_cairo: if HAS_CAIRO: if fmt == 'svg': surface = cairo.SVGSurface(outfile, size[0], size[1]) else: surface = cairo.PDFSurface(outfile, size[0], size[1]) mapnik.render(m, surface, scale_factor, 0, 0) surface.finish() else: mapnik.render_to_file(m, outfile, fmt) else: if options.tiles == 1: im = mapnik.Image(size[0], size[1]) mapnik.render(m, im, scale_factor) im.save(outfile, fmt) else: # we cannot make mapnik calculate scale for us, so fixing aspect ratio outselves rdiff = (bbox.maxx - bbox.minx) / (bbox.maxy - bbox.miny) - size[0] / size[1] if rdiff > 0: bbox.height((bbox.maxx - bbox.minx) * size[1] / size[0]) elif rdiff < 0: bbox.width((bbox.maxy - bbox.miny) * size[0] / size[1]) scale = (bbox.maxx - bbox.minx) / size[0] width = max(32, int(math.ceil(1.0 * size[0] / options.tiles))) height = max(32, int(math.ceil(1.0 * size[1] / options.tiles))) m.resize(width, height) m.buffer_size = TILE_BUFFER tile_cnt = [ int(math.ceil(1.0 * size[0] / width)), int(math.ceil(1.0 * size[1] / height)) ] logging.debug('tile_count=%s %s', tile_cnt[0], tile_cnt[1]) logging.debug('tile_size=%s,%s', width, height) # ----- BEGIN PRINTMAPS ----- # tmp_tile = '{:02d}_{:02d}_{}' tmp_tile = '{}_{:02d}_{:02d}' # ----- END PRINTMAPS ----- tile_files = [] for row in range(0, tile_cnt[1]): for column in range(0, tile_cnt[0]): logging.debug('tile=%s,%s', row, column) tile_bbox = mapnik.Box2d( bbox.minx + 1.0 * width * scale * column, bbox.maxy - 1.0 * height * scale * row, bbox.minx + 1.0 * width * scale * (column + 1), bbox.maxy - 1.0 * height * scale * (row + 1)) tile_size = [ width if column < tile_cnt[0] - 1 else size[0] - width * (tile_cnt[0] - 1), height if row < tile_cnt[1] - 1 else size[1] - height * (tile_cnt[1] - 1) ] m.zoom_to_box(tile_bbox) im = mapnik.Image(tile_size[0], tile_size[1]) mapnik.render(m, im, scale_factor) # ----- BEGIN PRINTMAPS ----- # tile_name = tmp_tile.format(row, column, options.output) tile_name = tmp_tile.format(options.output, row, column) # ----- END PRINTMAPS ----- im.save(tile_name, fmt) if options.just_tiles: # write ozi/wld for a tile if needed if '.' not in tile_name: tile_basename = tile_name + '.' else: tile_basename = tile_name[0:tile_name.rindex('.') + 1] if options.ozi: with open(tile_basename + 'ozi', 'w') as f: f.write( prepare_ozi(tile_bbox, tile_size[0], tile_size[1], tile_basename + '.ozi', transform)) if options.wld: with open(tile_basename + 'wld', 'w') as f: f.write( prepare_wld(tile_bbox, tile_size[0], tile_size[1])) else: tile_files.append(tile_name) if not options.just_tiles: # join tiles and remove them if joining succeeded import subprocess result = subprocess.call([ IM_MONTAGE, '-geometry', '+0+0', '-tile', '{}x{}'.format( tile_cnt[0], tile_cnt[1]) ] + tile_files + [options.output]) if result == 0: for tile in tile_files: os.remove(tile) if options.output == '-': if sys.platform == "win32": # fix binary output on windows import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) outfile.seek(0) sys.stdout.write(outfile.read()) outfile.close()
import cairo with cairo.SVGSurface("example.svg", 200, 200) as surface: c = cairo.Context(surface) c.scale(200, 200) c.set_line_width(0.05) c.move_to(1, 1) c.line_to(0.5, 0, 5) c.move_to(2, 1) c.line_to(-0.5, 0, 5) c.set_source_rgb(0, 0, 1) c.stroke()
def _prim_add_food(self, name, media, calories, protein, carbohydrates, fiber, fat): # Add a new food item to the palette palette = make_palette('food', colors=["#FFFFFF", "#A0A0A0"], help_string=_('Palette of foods')) # We need to convert the media into two svgs, one for the # palette and one for the block. filepath = None if media is not None and os.path.exists(media.value): filepath = media.value elif self.tw.running_sugar: # datastore object from sugar.datastore import datastore try: dsobject = datastore.get(media.value) except: debug_output("Couldn't find dsobject %s" % (media.value), self.tw.running_sugar) if dsobject is not None: filepath = dsobject.file_path if filepath is None: self.tw.showlabel('nojournal', filepath) return pixbuf = None try: pixbufsmall = gtk.gdk.pixbuf_new_from_file_at_size( filepath, 40, 40) pixbufoff = gtk.gdk.pixbuf_new_from_file_at_size(filepath, 40, 40) except: self.tw.showlabel('nojournal', filepath) debug_output("Couldn't open food image %s" % (filepath), self.tw.running_sugar) return def _draw_pixbuf(cr, pixbuf, x, y, w, h): # Build a gtk.gdk.CairoContext from a cairo.Context to access # the set_source_pixbuf attribute. cc = gtk.gdk.CairoContext(cr) cc.save() # center the rotation on the center of the image cc.translate(x + w / 2., y + h / 2.) cc.translate(-x - w / 2., -y - h / 2.) cc.set_source_pixbuf(pixbuf, x, y) cc.rectangle(x, y, w, h) cc.fill() cc.restore() if self.tw.running_sugar: path = os.path.join(get_path(self.tw.activity, 'instance'), 'output.svg') else: path = TMP_SVG_PATH svg_surface = cairo.SVGSurface(path, 40, 40) cr_svg = cairo.Context(svg_surface) _draw_pixbuf(cr_svg, pixbufsmall, 0, 0, 40, 40) cr_svg.show_page() svg_surface.flush() svg_surface.finish() destination = os.path.join(self.tw.path, 'plugins', 'food', 'images', name.encode('ascii') + 'small.svg') check_output(['mv', path, destination], 'problem moving %s to %s' % (path, destination)) pixbufsmall = gtk.gdk.pixbuf_new_from_file_at_size(destination, 40, 40) self.tw.media_shapes[name.encode('ascii') + 'small'] = pixbufsmall svg_surface = cairo.SVGSurface(path, 40, 40) cr_svg = cairo.Context(svg_surface) _draw_pixbuf(cr_svg, pixbufoff, 0, 0, 40, 40) cr_svg.show_page() svg_surface.flush() svg_surface.finish() destination = os.path.join(self.tw.path, 'plugins', 'food', 'images', name.encode('ascii') + 'off.svg') check_output(['mv', path, destination], 'problem moving %s to %s' % (path, destination)) # Now that we have the images, we can make the new block self._make_polynominal(palette, name.encode('ascii'), name, [calories, protein, carbohydrates, fiber, fat], expand=(15, 15)) pixbufoff = gtk.gdk.pixbuf_new_from_file_at_size(destination, 40, 40) self.tw.media_shapes[name.encode('ascii') + 'off'] = pixbufoff # Show the new block self.tw.show_toolbar_palette(palette_name_to_index('food'), regenerate=True) # Finally, we need to save new food item to a database so it # loads next time. food = name.encode('ascii') self.food_dictionary[food] = {} self.food_dictionary[food]['name'] = name self.food_dictionary[food]['calories'] = calories self.food_dictionary[food]['protein'] = protein self.food_dictionary[food]['carbohydrates'] = carbohydrates self.food_dictionary[food]['fiber'] = fiber self.food_dictionary[food]['fat'] = fat path = os.path.join(self.tw.path, 'plugins', 'food', 'food.db') data_to_file(self.food_dictionary, path) return
def _save(self, fo, format, **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 format == 'ps': if not cairo.HAS_PS_SURFACE: raise RuntimeError('cairo has not been compiled with PS ' 'support enabled') surface = cairo.PSSurface(fo, width_in_points, height_in_points) elif format == 'pdf': if not cairo.HAS_PDF_SURFACE: raise RuntimeError('cairo has not been compiled with PDF ' 'support enabled') surface = cairo.PDFSurface(fo, width_in_points, height_in_points) elif format in ('svg', 'svgz'): if not cairo.HAS_SVG_SURFACE: raise RuntimeError('cairo has not been compiled with SVG ' 'support enabled') if format == 'svgz': filename = fo if is_string_like(fo): fo = open(fo, 'wb') fo = gzip.GzipFile(None, 'wb', fileobj=fo) surface = cairo.SVGSurface(fo, width_in_points, height_in_points) else: warnings.warn("unknown format: %s" % format) 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.ctx if orientation == 'landscape': ctx.rotate(npy.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) show_fig_border = False # for testing figure orientation and scaling if show_fig_border: ctx.new_path() ctx.rectangle(0, 0, width_in_points, height_in_points) ctx.set_line_width(4.0) ctx.set_source_rgb(1, 0, 0) ctx.stroke() ctx.move_to(30, 30) ctx.select_font_face('sans-serif') ctx.set_font_size(20) ctx.show_text('Origin corner') ctx.show_page() surface.finish()
def export_cb (self, event): maxx, maxy = self.MainArea.get_max_area () x, y, width, height, bitdepth = self.MainArea.window.get_geometry () glade = Gtk.Builder() glade.add_from_file(utils.get_data_file_name('labyrinth.glade')) dialog = glade.get_object ('ExportImageDialog') box = glade.get_object ('dialog_insertion') fc = Gtk.FileChooserWidget(Gtk.FileChooserAction.SAVE) box.pack_end (fc) filter_mapping = [ (_('All Files'), ['*']), (_('PNG Image (*.png)'), ['*.png']), (_('JPEG Image (*.jpg, *.jpeg)'), ['*.jpeg', '*.jpg']), (_('SVG Vector Image (*.svg)'), ['*.svg']), (_('PDF Portable Document (*.pdf)'), ['*.pdf']) ] for (filter_name, filter_patterns) in filter_mapping: fil = Gtk.FileFilter () fil.set_name(filter_name) for pattern in filter_patterns: fil.add_pattern(pattern) fc.add_filter(fil) fc.set_current_name ("%s.png" % self.main_window.title) rad = glade.get_object ('rb_complete_map') rad2 = glade.get_object ('rb_visible_area') self.spin_width = glade.get_object ('width_spin') self.spin_height = glade.get_object ('height_spin') self.spin_width.set_value (maxx) self.spin_height.set_value (maxy) self.spin_width.set_sensitive (False) self.spin_height.set_sensitive (False) rad.connect ('toggled', self.toggle_range, width, height,maxx,maxy) fc.show () while 1: # Cheesy loop. Break out as needed. response = dialog.run() if response == Gtk.ResponseType.OK: ext_mime_mapping = { 'png':'png', 'jpg':'jpeg', 'jpeg':'jpeg', \ 'svg':'svg', 'pdf':'pdf' } filename = fc.get_filename() ext = filename[filename.rfind('.')+1:] try: mime = ext_mime_mapping[ext] break except KeyError: msg = Gtk.MessageDialog(self, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, \ _("Unknown file format")) msg.format_secondary_text (_("The file type '%s' is unsupported. Please use the suffix '.png',"\ " '.jpg' or '.svg'." % ext)) msg.run () msg.destroy () else: dialog.destroy () return true_width = int (self.spin_width.get_value ()) true_height = int (self.spin_height.get_value ()) native = not rad.get_active () dialog.destroy () if mime in ['png', 'jpg']: self.save_as_pixmap(filename, mime, true_width, true_height, bitdepth, native) else: surface = None if mime == 'svg': surface = cairo.SVGSurface(filename, true_width, true_height) elif mime == 'pdf': surface = cairo.PDFSurface(filename, true_width, true_height) self.save_surface(surface, true_width, true_height, native)
SetRGB(self.color) c.rectangle(self.x, self.y, self.w, self.h) if self.fill: c.fill() else: c.stroke() self.x = self.xLambda(self.x, self.dx) self.y = self.yLambda(self.y, self.dy) self.w = self.yLambda(self.w, self.dw) self.w = self.yLambda(self.h, self.dh) FRAMES_PER_SECOND = 24 WIDTH = 600 HEIGHT = 600 s = cairo.SVGSurface("surface.svg", WIDTH, HEIGHT) c = cairo.Context(s) # rectangle1 : background rectangle that condenses into the center # rectangle2 : background rectangle that expands from the center # rectangle3u : quick vertical line that shoots up and expands across the screen horizontally # rectangle3r : quick vertical line that shoots right and expands across the screen vertically # rectangle3d : quick vertical line that shoots down and expands across the screen horizontally # rectangle3l : quick vertical line that shoots left and expands across the screen vertically colors = FormatColors( ["edf2fb", "e2eafc", "d7e3fc", "ccdbfd", "c1d3fe", "b6ccfe", "abc4ff"]) keyPressInfo = json.loads(open("keypressinfo.json").read()) keyPresses = json.loads(open("keypresses.json").read())
def main(): """Main function""" # Image surfaces provide the ability to render to memory buffers either # allocated by cairo or by the calling code. # List of supported surfaces: http://www.cairographics.org/manual/cairo-surfaces.html surface = cairo.SVGSurface("fill_and_stroke.svg", WIDTH, HEIGHT) # cairo.Context is the object that you send your drawing commands to. context = cairo.Context(surface) # Normalizing the canvas ([0,1],[0,1]) -> ([0,WIDTH],[0,HEIGHT]) context.scale(WIDTH, HEIGHT) ### DRAW ### # context.set_source_rgb(0., 0., 0.) # context.set_source_rgba(0., 0., 0., 1.) # Sets the source pattern within context to an opaque color. This opaque color # will then be used for any subsequent drawing operation until a new source # pattern is set. # The color components are floating point numbers in the range 0 to 1. If # the values passed in are outside that range, they will be clamped. # The default source pattern is opaque black, (that is, it is equivalent to # cairo_set_source_rgb(context, 0.0, 0.0, 0.0)). # Using set_source_rgb(r, g, b) is equivalent to using # set_source_rgba(r, g, b, 1.0), and it sets your source color to use # full opacity. # # context.stroke() # The stroke() operation takes a virtual pen along the current path # according to the current line width, line join, line cap, and dash # settings. After cairo_stroke(), the current path will be cleared from # the cairo context. # See http://www.cairographics.org/manual/cairo-cairo-t.html#cairo-stroke # # context.fill() # A drawing operator that fills the current path according to the current # fill rule, (each sub-path is implicitly closed before being filled). # After cairo_fill(), the current path will be cleared from the cairo # context. # See http://www.cairographics.org/manual/cairo-cairo-t.html#cairo-fill context.set_line_width(0.03) # WHITE BACKGROUND context.set_source_rgb(1, 1, 1) context.rectangle(0, 0, 1, 1) context.fill() # FILL... context.set_source_rgba(1, 0.2, 0.2, 0.6) context.rectangle(0.1, 0.1, 0.3, 0.3) context.rectangle(0.1, 0.6, 0.3, 0.3) context.rectangle(0.6, 0.1, 0.3, 0.3) context.rectangle(0.6, 0.6, 0.3, 0.3) context.fill_preserve() # <- PRESERVE PATH FOR STROKE !!! # ...AND STROKE context.set_source_rgb(0, 0, 0) context.stroke() ### WRITE THE SVG FILE ### surface.finish()
def plot_image_subregion( raw_im, mean_im, absdiff_im, roiradius, fname, user_coords, scale=4.0, view="orig", extras=None, ): if extras is None: extras = {} output_ext = os.path.splitext(fname)[1].lower() roisize = 2 * roiradius imtypes = ["raw", "absdiff", "mean"] margin = 10 square_edge = roisize * scale width = int( round(len(imtypes) * square_edge + (len(imtypes) + 1) * margin)) height = int(round(square_edge + 2 * margin)) if output_ext == ".pdf": output_surface = cairo.PDFSurface(fname, width, height) elif output_ext == ".svg": output_surface = cairo.SVGSurface(fname, width, height) elif output_ext == ".png": output_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) else: raise ValueError("unknown output extension %s" % output_ext) ctx = cairo.Context(output_surface) # fill with white ctx.set_source_rgb(1, 1, 1) ctx.rectangle(0, 0, width, height) ctx.fill() user_l, user_b, user_r, user_t = user_coords # setup transform # calculate image boundary (user coords) for im_idx, im in enumerate(imtypes): if im == "raw": display_im = raw_im elif im == "mean": display_im = mean_im elif im == "absdiff": display_im = np.clip(5 * absdiff_im, 0, 255) # set transform - make a patch of the cairo # device be addressed with our image space # coords device_l = (im_idx + 1) * margin + im_idx * square_edge device_b = margin ctx.identity_matrix() # reset if view == "orig": matrix = cairo.Matrix( xx=scale, yx=0, xy=0, yy=scale, x0=(device_l - scale * user_l), y0=(device_b - scale * user_b), ) elif view == "rot -90": matrix = cairo.Matrix( xx=0, yx=scale, xy=scale, yy=0, x0=(device_l - scale * user_b), y0=(device_b - scale * user_l), ) elif view == "rot 180": matrix = cairo.Matrix( xx=-scale, yx=0, xy=0, yy=-scale, x0=(device_l + scale * user_r), y0=(device_b + scale * user_t), ) else: raise ValueError("unknown view '%s'" % view) ctx.set_matrix(matrix) ## print 'device_l-user_l, device_b-user_b',device_l-user_l, device_b-user_b ## #ctx.translate(device_l-user_l, device_b-user_b) ## if scale!= 1.0: ## ctx.scale( scale, scale ) ## #raise NotImplementedError('') ## ctx.translate(device_l-user_l, device_b-user_b) ## #print 'square_edge/roisize, square_edge/roisize',square_edge/roisize, square_edge/roisize ## #ctx.scale( roisize/square_edge, square_edge/roisize) if 1: in_surface = benu.numpy2cairo(display_im.astype(np.uint8)) ctx.rectangle(user_l, user_b, display_im.shape[1], display_im.shape[0]) if 1: ctx.save() ctx.set_source_surface(in_surface, user_l, user_b) ctx.paint() ctx.restore() else: ctx.set_source_rgb(0, 0.3, 0) ctx.fill() if 0: ctx.move_to(user_l, user_b) ctx.line_to(user_r, user_b) ctx.line_to(user_r, user_t) ctx.line_to(user_l, user_t) ctx.line_to(user_l, user_b) ctx.close_path() ctx.set_source_rgb(0, 1, 0) ctx.fill() ctx.move_to(user_l + 5, user_b + 5) ctx.line_to(user_r - 40, user_b + 5) ctx.line_to(user_r - 40, user_t - 40) ctx.line_to(user_l + 5, user_t - 40) ctx.line_to(user_l + 5, user_b + 5) ctx.close_path() ctx.set_source_rgb(0, 0, 1) ctx.fill() if output_ext == ".png": output_surface.write_to_png(fname) else: ctx.show_page() output_surface.finish()