def draw_line_with_colours(start_x, start_y, stop_x, stop_y, drawing: Drawing, colours): number_of_colours = len(colours) initial_offset = number_of_colours / 2 counter = 0 for colour in colours: x_diff = stop_x - start_x y_diff = stop_y - start_y offset = initial_offset - counter counter += 1 if x_diff == 0: drawing.append(draw.Line(start_x + offset, start_y, stop_x + offset, stop_y, stroke=colour, stroke_width=1)) else: y2 = 1 y1 = -(y_diff/x_diff) length = np.sqrt(y1 * y1 + y2) y1_norm = y1 / length y2_norm = y2 / length drawing.append(draw.Line(start_x + y1_norm * offset, start_y + y2_norm * offset, stop_x + y1_norm * offset, stop_y + y2_norm * offset, stroke=colour, stroke_width=1))
def state_text(self, g, time, key, amp=1): state_idx = self.possible_states.index(key) x, y = self.state_xy(key, time) g.draw(render_label(sympy.sympify(amp), key), x=x + self.w_label / 2 - self.font * 0.2, y=y, scale=self.font / 12, center=True, text_anchor='end') if abs(float(amp)) < 1e-8: # Draw red X over it ys = self.font / 2 * 1.4 xs = self.w_label / 2 * 0.7 xf = self.font g.append( draw.Line(x + xf - xs, y - ys, x + xf + xs, y + ys, stroke='red', stroke_width=1)) g.append( draw.Line(x + xf - xs, y + ys, x + xf + xs, y - ys, stroke='red', stroke_width=1))
def draw_harbours(self, harbour_list): for col, row, adj_tiles, harbour_type in harbour_list: c_x, c_y = self._get_hexagon_coords(col, row) t = draw.Text(harbour_type, 42, c_x, -c_y, center=True, stroke="lime") c = draw.Circle(c_x, -c_y, r=32, fill="white", stroke="black") n = set( chain.from_iterable([(a, b) for _, _, type, a, b in adj_tiles if not type == 'harbour'])) # 0 = 90° theta, 1= 30*, 2 = -30°, 3 = - 90° for corner in n: theta = 90 - corner * 60 e_x = int(self.HALF_TILE * np.math.cos(np.math.radians(theta)) + c_x) e_y = int(self.HALF_TILE * np.math.sin(np.math.radians(theta)) + c_y) line = draw.Line(c_x, -c_y, e_x, -e_y, **{ "stroke": "red", "stroke-width": "5px" }) self.drawing.extend([line]) self.drawing.extend([c, t])
def draw(self, string): for char in string: if char in CHAR_TO_DRAW_FN: # Ignore variables getattr(self, CHAR_TO_DRAW_FN[char])() all_x_0, all_y_0, all_x_1, all_y_1 = zip(*self.lines) min_x = min(all_x_0 + all_x_1) max_x = max(all_x_0 + all_x_1) min_y = min(all_y_0 + all_y_1) max_y = max(all_y_0 + all_y_1) length_x = max_x - min_x length_y = max_y - min_y longer = max(length_x, length_y) shift_x = (1000 - (length_x * 1000 / longer)) / 2 # take half of remaining white space shift_y = (1000 - (length_y * 1000 / longer)) / 2 new_x0 , new_x1 , new_y0 , new_y1 = [],[],[],[] for old_x0, old_y0, old_x1, old_y1 in self.lines: new_x0.append((old_x0 - min_x)*1000/longer + shift_x) new_x1.append((old_x1 - min_x)*1000/longer + shift_x) new_y0.append((old_y0 - min_y)*1000/longer + shift_y) new_y1.append((old_y1 - min_y) * 1000 / longer + shift_y) new_points = zip(new_x0, new_y0, new_x1, new_y1) for p in new_points: self.drawing.append(draw.Line(*p, stroke='black'))
def Line(self, sx: float, sy: float, ex: float, ey: float, width: int, color: str) -> draw.Line: return draw.Line(sx, self.height - sy, ex, self.height - ey, stroke_width=width, stroke=color)
def straight_arrow(self, g, color, *xy_list, width=1): rev_xy = xy_list[::-1] rev_xy = [rev_xy[i+1-2*(i%2)] for i in range(len(rev_xy))] w = 3 * width g.append(draw.Line(*rev_xy, stroke=color, stroke_width=w, fill='none', # Pull the line behind the arrow stroke_dasharray=f'0 {w*4/2} 1000000', marker_start=self.make_arrow(color)))
def draw_segment(self, p, q): c = draw.Line( p.x, p.y, q.x, q.y, stroke='blue', stroke_width=.5, ) self.context.append(c)
def drawFret(self, d: dsvg.Drawing, x: float, y: float, strings: int) -> float: fs = self.fretStyle fretBoardHeight = (strings - 1) * fs.fretHeight d.append( dsvg.Line(x, y, x, y - fretBoardHeight, stroke_width=stringWidth, stroke=stringColor)) return fs.fretWidth
def draw_legend(d): d.append(draw.Circle(250, 320, 20, fill="yellow", stroke="orange")) d.append( draw.Line(0, 0, 0, 200, stroke_width=2, stroke="red", fill="yellow", transform="translate(250, -320) rotate(-80)")) d.append(draw.Circle(550, 320, 20, fill="yellow", stroke="orange")) d.append( draw.Line(0, -100, 0, 100, stroke_width=2, stroke="green", fill="yellow", transform="translate(550, -320) rotate(-30)"))
def drawString(self, d: dsvg.Drawing, lowerFret: int, upperFret: int, x: float, y: float) -> float: fs = self.frets[0].fretStyle fretWidth = fs.fretWidth stringLength = (upperFret - lowerFret + 1) * fretWidth d.append( dsvg.Line(x, y, x + stringLength, y, stroke_width=stringWidth * pow(1.1, self.stringIndex), stroke=stringColor)) return fs.fretHeight
def draw(self, x=0, y=0, xscale=1.0): h = self.h a = self.x * xscale b = (self.x + self.w) * xscale x = x * xscale r = h / 2 font_size = h * 0.55 arrow_size = 7 if self.direction >= 0: line_start = a arrow_end = b arrow_start = max(arrow_end - arrow_size, line_start) else: line_start = b arrow_end = a arrow_start = min(arrow_end + arrow_size, line_start) centre = (a + b) / 2 arrow_y = h / 2 + self.elevation * r group = draw.Group(transform="translate({} {})".format(x, y)) group.append( draw.Line(line_start, arrow_y, arrow_start, arrow_y, stroke='black')) group.append( draw.Circle(centre, h / 2, r, fill='ivory', stroke='black')) group.append( draw.Lines(arrow_end, arrow_y, arrow_start, arrow_y + arrow_size / 2, arrow_start, arrow_y - arrow_size / 2, arrow_end, arrow_y, fill='black')) group.append( draw.Text(self.label, font_size, centre, h / 2, text_anchor='middle', dy="0.35em")) return group
def draw_component_positions(filename, drawing, bottom_layer=False): file = open(filename, 'r') offset_x, offset_y, *temp = file.readline().replace(',', '.').split('|') file.readline() # Skip empty line for entry in file: name, tele_id, x, y, rotation = entry.replace(',', '.').rstrip().split('|') x = float(x) + float(offset_x) y = float(y) + float(offset_y) x = x * factor y = y * factor if bottom_layer: y = output_image_height - y rotation = int(rotation) + 180 drawing.append( draw.Circle(x, y, 0.3 * factor, fill="yellow")) rotation_transform = str.format( "translate({1}, {2}) rotate({0}) ", str(-int(rotation)), str(x), str(-y)) drawing.append( draw.Line(0, 0, 0, 1 * factor, stroke="red", stroke_width=2, transform=rotation_transform)) if name in part_package: package = part_package[name] if package in first_pads: pad_position = first_pads[package] pad_x = pad_position[0] * factor pad_y = pad_position[1] * factor angle_rad = radians(int(rotation)) rot_x = pad_x * math.cos(angle_rad) - pad_y * math.sin(angle_rad) rot_y = pad_x * math.sin(angle_rad) + pad_y * math.cos(angle_rad) rotation_transform = str.format( "translate({1}, {2}) rotate({0})", str(-int(rotation)), str(x), str(-y)) drawing.append(draw.Circle(pad_x, pad_y, 0.2 * factor, fill="blue", transform=rotation_transform)) drawing.append( draw.Text(name, 1 * factor, x - rot_x, y + rot_y, stroke="#444444", fill="lightgreen"))
def draw(self): self.update() count = len(self.levels) w = count * 100 + 20 h = count * 100 + 20 d = draw.Drawing(w + 50, h, origin=(0, 0)) for i in range(count): cheight = i * self.height + 10 els = self.subs[i].draw(retEls=True, off=(0, cheight)) for j in range(len(els)): d.append(els[j]) l = draw.Line(0, cheight - 10, self.width + 50, cheight - 10, stroke="black", stroke_width=0.5, fill=None) d.append(l) return d
def drawSigil(points, canvas, color='white'): # draw sigil from coordinate list # setup sigil dash = svg.Marker(-0.5, -0.5, 0.5, 0.5, scale=5, orient='auto') # define line to terminate the sigil dash.append(svg.Line(-0., -0.5, 0., 0.5, stroke_width=0.2, stroke=color)) dot = svg.Marker(-0.8, -0.5, 0.5, 0.5, scale=5, orient='auto') # define circle to start the sigil dot.append(svg.Circle(-0.3, 0.0, 0.3, stroke_width=0.2, stroke=color, fill='none')) p = svg.Path(stroke_width=7, stroke=color, fill='none', marker_start=dot, marker_end=dash) # draw sigil for point in points: if points.index(point) == 0: originX = point[0] originY = point[1] p.M(originX, originY) else: x = point[0] - originX # abs. to rel. coords y = point[1] - originY # abs. to rel. coords p.l(x, y) # draw originX = point[0] originY = point[1] # add to canvas canvas.append(p)
def render(self, dpi=96, background=None): # self.printState() # TODO: implement polyline d = draw.Drawing(self.diameter, self.diameter, origin='center') radius = self.diameter / 2.0 if background is not None: d.append( draw.Rectangle(-radius, -radius, self.diameter, self.diameter, fill=background)) d.append( draw.Circle(0, 0, radius, stroke='black', stroke_width=5, stroke_opacity=1, fill='none')) for i in range(self.n_pins - 1, 0, -1): for j in range(0, i): for yarn in self.state[i][j]: endPoint = self._get_point(i) startPoint = self._get_point(j) d.append( draw.Line(startPoint.x, startPoint.y, endPoint.x, endPoint.y, stroke_width=yarn.width, stroke=yarn.color, stroke_opacity=0.4, fill='none')) d.setPixelScale(dpi * 0.393701 / 10) return d
f1 = open( sys.argv[1], 'r' ) contents = list(filter(str.strip, f1.readlines())) f1.close() inputInfo = contents[0] contents.remove(contents[0]) inputInfo = inputInfo.replace('\n', '').split(' ') inputNum = int(inputInfo[-1]) X = 3*(len(contents)+5) Y = 3*(inputNum+3) d = draw.Drawing(X,Y) for i in range(inputNum): d.append(draw.Text(str(i)+'\'',3, X-3,i*3+6-1)) d.append(draw.Text(str(i),3, 1.5,i*3+6-1)) d.append(draw.Line(6,i*3+6,X-6,i*3+6,stroke_width=0.2, stroke='black')) for i, content in enumerate(contents): content = content.split() ctrl = int(content[0]) target = int(content[1]) d.append(draw.Line(9+i*3,ctrl*3+6, 9+i*3,target*3+6,stroke_width=0.2, stroke='black')) d.append(draw.Circle(9+i*3,ctrl*3+6, 0.5)) d.append(draw.Circle(9+i*3,target*3+6, 0.75,fill='white', fill_opacity=0.0, stroke_width=0.2, stroke='black')) d.append(draw.Line(9+i*3-0.75,target*3+6, 9+i*3+0.75,target*3+6,stroke_width=0.2, stroke='black')) d.append(draw.Line(9+i*3,target*3+6-0.75, 9+i*3,target*3+6+0.75,stroke_width=0.2, stroke='black')) d.setPixelScale(1080/Y) # Set number of pixels per geometry unit #d.setRenderSize(400,200) # Alternative to setPixelScale d.saveSvg(sys.argv[2]+".svg") d.savePng(sys.argv[2]+".png")
def draw_catdog(name, param): """ Draws a cat/dog and saves it as an svg Parameters ---------- name : string Filename to save catdog as param : dictionary (keys: variables list) Variable values for the structure of the face """ full_dwg = draw.Drawing(800, 600) dwg = draw.Group() full_dwg.append(dwg) width = 173*(param["face_aspect_ratio"])**0.5 height = 173/(param["face_aspect_ratio"])**0.5 cx = 800/2 cy = 600/2 #Ears ear_angle = param["ear_angle"] ear_tip_angle = param["ear_tip_angle"] ear_length = param["ear_length"] ear_orientation = param["ear_orientation"] ear_point = param["ear_point"] eye_height = param["eye_height"] eye_width = eye_height*param["eye_aspect_ratio"] eye_distance = param["eye_distance"] nose_size = param["nose_size"] fur_color = "hsl(%i, %i%%, %i%%)" % (45,param["fur_saturation"],param["fur_lightness"]) dist_to_tip = r_ellipse(ear_angle,width,height)+ear_length right_tip = dir_point((cx,cy),dist_to_tip,ear_angle) bottom_right = dir_point(right_tip,ear_length*2.2,180+ear_angle+ear_tip_angle*ear_orientation) bottom_right_ctrl = dir_point(bottom_right,ear_length*2.2-ear_point,ear_angle+ear_tip_angle*ear_orientation) top_right = dir_point(right_tip,ear_length*2.2,180+ear_angle-ear_tip_angle*(1-ear_orientation)) top_right_ctrl = dir_point(top_right,ear_length*2.2-ear_point,ear_angle-ear_tip_angle*(1-ear_orientation)) top_left, top_left_ctrl, left_tip, bottom_left_ctrl, bottom_left = mirror([top_right, top_right_ctrl, right_tip, bottom_right_ctrl, bottom_right],cx) left_ear = draw.Path(stroke_width = 1, stroke='black', fill = fur_color) left_ear.M(*bottom_left) left_ear.L(*bottom_left_ctrl) left_ear.A(ear_point*.8, ear_point*.8, 0, False, True, *top_left_ctrl) left_ear.L(*top_left) right_ear = draw.Path(stroke_width = 1, stroke='black', fill = fur_color) right_ear.M(*bottom_right) right_ear.L(*bottom_right_ctrl) right_ear.A(ear_point*.8, ear_point*.8, 0, False, False, *top_right_ctrl) right_ear.L(*top_right) dwg.draw(left_ear) dwg.draw(right_ear) #Face face = ellipse(cx, cy, width, height, stroke_width = 1, stroke='black', fill = fur_color) dwg.draw(face) #Eyes left_eye = ellipse(cx-eye_distance, cy+height/4, eye_width, eye_height, stroke_width = 1, stroke='black', fill = "black") right_eye = ellipse(cx+eye_distance, cy+height/4, eye_width, eye_height, stroke_width = 1, stroke='black', fill = "black") dwg.draw(left_eye) dwg.draw(right_eye) #Nose dwg.draw(draw.Lines(cx-nose_size, cy+nose_size/3, cx+nose_size, cy+nose_size/3, cx,cy-nose_size, close=True, stroke_width = 1, stroke='black', fill = "black")) #Snout dwg.draw(draw.Line(cx,cy-nose_size,cx,cy-nose_size*2.5, stroke_width = 2, stroke='black', fill = "black")) #Mouth mouth = draw.Path(fill = "none", stroke_width = 2, stroke = 'black') mouth.M(cx-nose_size*2,cy-nose_size*2.5-4) mouth.A(nose_size*2, nose_size*2, 30, False, False, cx, cy-nose_size*2.5) mouth.A(nose_size*2, nose_size*2, 150, False, False, cx+nose_size*2, cy-nose_size*2.5-4) dwg.draw(mouth) #Whiskers whisker_length = param["whisker_length"] whiskers = [((cx-34,cy-nose_size-10),195), ((cx-40,cy-nose_size-4),185), ((cx-34,cy-nose_size+2),175), ((cx+34,cy-nose_size-10),345), ((cx+40,cy-nose_size-4),355), ((cx+34,cy-nose_size+2),5) ] for whisker in whiskers: dwg.draw(draw.Line(*whisker[0],*dir_point(whisker[0],whisker_length,whisker[1]), stroke_width = 1, stroke='black', fill = "black")) full_dwg.saveSvg(name)
cw=True, stroke='blue', stroke_width=1, fill='black', fill_opacity=0.3)) # Draw arrows arrow = draw.Marker(-0.1, -0.5, 0.9, 0.5, scale=4, orient='auto') arrow.append(draw.Lines(-0.1, -0.5, -0.1, 0.5, 0.9, 0, fill='red', close=True)) p = draw.Path(stroke='red', stroke_width=2, fill='none', marker_end=arrow) # Add an arrow to the end of a path p.M(20, -40).L(20, -27).L(0, -20) # Chain multiple path operations d.append(p) d.append( draw.Line(30, -20, 0, -10, stroke='red', stroke_width=2, fill='none', marker_end=arrow)) # Add an arrow to the end of a line d.setPixelScale(2) # Set number of pixels per geometry unit #d.setRenderSize(400,200) # Alternative to setPixelScale d.saveSvg('example.svg') d.savePng('example.png') # Display in Jupyter notebook d.rasterize() # Display as PNG d # Display as SVG
def draw_bloch_sphere(d, inner_proj=euclid3d.identity(3), label='', axis=None, rot_proj=None, rot_deg=180, outer_labels=(), inner_labels=(), extra_opacity=1, inner_opacity=1, background='white'): spin = euclid3d.rotation(3, 0, 2, 2 * np.pi / 16 / 2 * 1.001) tilt = euclid3d.rotation(3, 1, 2, np.pi / 8) trans = tilt @ spin @ euclid3d.axis_swap((1, 2, 0)) proj = euclid3d.perspective3d(np.pi / 8, view_size=4) @ trans zx = euclid3d.axis_swap((2, 0, 1)) xy = euclid3d.identity(3) yz = euclid3d.axis_swap((1, 2, 0)) proj_zx = proj @ zx proj_xy = proj @ xy proj_yz = proj @ yz if background: d.append(draw.Rectangle(-100, -100, 200, 200, fill=background)) def draw_band(proj, trans, r_outer=1, r_inner=0.9, color='black', z_mul=1, opacity=1, divs=4, d=d, **kwargs): color = (color * divs)[:divs] if isinstance(color, list) else [color] * divs points = np.array([[-1, -1, 1, 1], [-1, 1, 1, -1]]).T sqr12 = 0.5**0.5 overlap = np.pi / 500 * (divs != 4) start_end_points = [ np.array([[ np.cos(pr - 2 * np.pi / divs - overlap), np.sin(pr - 2 * np.pi / divs - overlap) ], [np.cos(pr + overlap), np.sin(pr + overlap)], [np.cos(pr - np.pi / divs), np.sin(pr - np.pi / divs)]]) for pr in np.linspace(0, 2 * np.pi, num=divs, endpoint=False) ] for i in range(divs): p = draw.Path(fill=color[i], stroke='none', stroke_width=0.002, **kwargs, opacity=opacity) z = trans.project_point( (r_inner + r_outer) / 2 * start_end_points[i][2])[2] e = shapes.EllipseArc.fromBoundingQuad( *proj.project_list(points * r_outer)[:, :2].flatten(), *proj.project_list(start_end_points[i] * r_outer)[:, :2].flatten(), ) if e: e.drawToPath(p) if r_inner > 0: e = shapes.EllipseArc.fromBoundingQuad( *proj.project_list(points * r_inner)[:, :2].flatten(), *proj.project_list(start_end_points[i] * r_inner)[:, :2].flatten(), ) if e: e.reversed().drawToPath(p, includeL=True) p.Z() d.append(p, z=z * z_mul) if False: d.draw(shapes.EllipseArc.fromBoundingQuad( *proj.project_list( (r_outer + r_inner) / 2 * points)[:, :2].flatten(), *proj.project_list((r_outer + r_inner) / 2 * start_end_points[i])[:, :2].flatten(), ), fill='none', stroke_width=0.02, stroke=color[i], **kwargs, z=z * z_mul) xycolors = ['#56e', '#239', '#56e', '#56e'] yzcolors = ['#e1e144', '#909022', '#e1e144', '#e1e144'] zxcolors = ['#9e2', '#6a1', '#9e2', '#9e2'] draw_band(proj_xy, trans @ xy, 1, 0.925, z_mul=10, color=xycolors) draw_band(proj_yz, trans @ yz, 1, 0.925, z_mul=10, color=yzcolors) draw_band(proj_zx, trans @ zx, 1, 0.925, z_mul=10, color=zxcolors) # Inner g = draw.Group(opacity=inner_opacity) z_center = trans.project_point((0, 0, 0))[2] d.append(g, z=z_center) inner_xy = proj @ inner_proj @ xy # Darker colors: #34b, #a8a833, #7b2 draw_band(proj @ inner_proj @ xy, trans @ inner_proj @ xy, 0.8, 0.7, color=xycolors, d=g) draw_band(proj @ inner_proj @ yz, trans @ inner_proj @ yz, 0.8, 0.7, color=yzcolors, divs=4, d=g) draw_band(proj @ inner_proj @ zx, trans @ inner_proj @ zx, 0.8, 0.7, color=zxcolors, divs=8 // 2, d=g) elevation_lines = False if elevation_lines: for elevation in (*np.linspace(0, np.pi / 2, 4, True)[1:-1], *np.linspace(-np.pi / 2, 0, 3, False)[1:]): y = 0.75 * np.sin(elevation) r = 0.75 * np.cos(elevation) draw_band(proj @ inner_proj @ xy @ euclid3d.translation((0, 0, y)), trans @ inner_proj @ xy @ euclid3d.translation( (0, 0, y)), r_outer=r - 0.01, r_inner=r + 0.01, color='#bbb', opacity=1, d=g) arrow = draw.Marker(-0.1, -0.5, 0.9, 0.5, scale=4, orient='auto') arrow.append( draw.Lines(-0.1, -0.5, -0.1, 0.5, 0.9, 0, fill='black', close=True)) g.append(draw.Line(*inner_xy.p2(-0.65, 0, 0), *inner_xy.p2(0.6, 0, 0), stroke='black', stroke_width=0.015, marker_end=arrow), z=z_center) g.append(draw.Line(*inner_xy.p2(0, -0.65, 0), *inner_xy.p2(0, 0.6, 0), stroke='black', stroke_width=0.015, marker_end=arrow), z=z_center) g.append(draw.Line(*inner_xy.p2(0, 0, -0.65), *inner_xy.p2(0, 0, 0.6), stroke='black', stroke_width=0.015, marker_end=arrow), z=z_center) for pt, (x_off, y_off), elem in inner_labels: x, y = (proj @ inner_proj).p2(*pt) g.append(draw.Use(elem, x + x_off, y + y_off), z=10000) # Outer arrows and text arrow = draw.Marker(-0.1, -0.5, 0.9, 0.5, scale=4, orient='auto') arrow.append( draw.Lines(-0.1, -0.5, -0.1, 0.5, 0.9, 0, fill='black', close=True)) d.append(draw.Line(*proj_xy.p2(1, 0, 0), *proj_xy.p2(1.2, 0, 0), stroke='black', stroke_width=0.02, marker_end=arrow), z=100) d.append(draw.Line(*proj_xy.p2(0, 1, 0), *proj_xy.p2(0, 1.2, 0), stroke='black', stroke_width=0.02, marker_end=arrow), z=100) d.append(draw.Line(*proj_xy.p2(0, 0, 1), *proj_xy.p2(0, 0, 1.2), stroke='black', stroke_width=0.02, marker_end=arrow), z=100) d.append( draw.Line(*proj_xy.p2(-1, 0, 0), *proj_xy.p2(-1.2, 0, 0), stroke='black', stroke_width=0.02)) d.append( draw.Line(*proj_xy.p2(0, -1, 0), *proj_xy.p2(0, -1.2, 0), stroke='black', stroke_width=0.02)) d.append( draw.Line(*proj_xy.p2(0, 0, -1), *proj_xy.p2(0, 0, -1.2), stroke='black', stroke_width=0.02)) d.append(draw.Text(['X'], 0.2, *proj_xy.p2(1.7, 0, 0), center=True, fill='black'), z=100) d.append(draw.Text(['Y'], 0.2, *proj_xy.p2(0, 1.35, 0), center=True, fill='black'), z=100) d.append(draw.Text(['Z'], 0.2, *proj_xy.p2(0, 0, 1.4), center=True, fill='black'), z=100) for pt, (x_off, y_off), elem in outer_labels: x, y = proj.p2(*pt) d.append(draw.Use(elem, x + x_off, y + y_off), z=10000) # Extra annotations #label='', axis=None, rot_proj=None if label: d.append( draw.Text([label], 0.4, -0.6, 1.2, center=True, fill='#c00', text_anchor='end', opacity=extra_opacity)) if axis: g = draw.Group(opacity=extra_opacity) axis = np.array(axis, dtype=float) axis_len = 1.18 axis /= np.linalg.norm(axis) arrow = draw.Marker(-0.1, -0.5, 0.9, 0.5, scale=3, orient='auto') arrow.append( draw.Lines(-0.1, -0.5, -0.1, 0.5, 0.9, 0, fill='#e00', close=True)) z = 100 #10 * proj_xy.project_point(axis*1)[2] g.append( draw.Line(*proj_xy.p2(0, 0, 0), *proj_xy.p2(*axis * axis_len), stroke='#e00', stroke_width=0.04, marker_end=arrow)) d.append(g, z=z) if rot_proj is not None: rot_proj = inner_proj @ rot_proj r_inner, r_outer = 0.1, 0.16 points = np.array([[-1, -1, 1, 1], [-1, 1, 1, -1]]).T start_end_points = np.array([[1, 0], [-1, 0], [0, 1]]) p = draw.Path(fill='orange', fill_rule='nonzero', opacity=extra_opacity) z = 9 * (trans @ rot_proj).project_point(start_end_points[2])[2] e = shapes.EllipseArc.fromBoundingQuad( *(proj @ rot_proj).project_list(points * r_outer)[:, :2].flatten(), *(proj @ rot_proj).project_list(start_end_points * r_outer)[:, :2].flatten(), ) if e: e.reversed().drawToPath(p) e = shapes.EllipseArc.fromBoundingQuad( *(proj @ rot_proj).project_list(points * r_inner)[:, :2].flatten(), *(proj @ rot_proj).project_list(start_end_points * r_inner)[:, :2].flatten(), ) if e: e.drawToPath(p, includeL=True) sa = 2.5 * (r_outer - r_inner) xa = -(r_inner + r_outer) / 2 p.L(*(proj @ rot_proj).p2(xa, 0.3 * sa)) p.L(*(proj @ rot_proj).p2(xa + 0.5 * sa, 0.3 * sa)) p.L(*(proj @ rot_proj).p2(xa, -0.7 * sa)) p.L(*(proj @ rot_proj).p2(xa - 0.5 * sa, 0.3 * sa)) p.L(*(proj @ rot_proj).p2(xa, 0.3 * sa)) p.Z() d.append(p, z=z) return d
Maxx = max(coords[:, 0]) minx = min(coords[:, 0]) Maxy = max(coords[:, 1]) miny = min(coords[:, 1]) X = 3 * (Maxx + 3) Y = 3 * (Maxy + 3) d = draw.Drawing(X, Y) for _id in ids: [x, y] = id2Coord[_id] for neighbor in id2Neighbor[_id]: [_x, _y] = id2Coord[neighbor] d.append( draw.Line(3 * x + 3, 3 * y + 3, 3 * _x + 3, 3 * _y + 3, stroke_width=0.1, stroke='black')) for _id in ids: [x, y] = id2Coord[_id] d.append( draw.Circle(3 * x + 3, 3 * y + 3, 0.75, fill='white', fill_opacity=1, stroke_width=0.1, stroke='black')) d.append(draw.Text(str(_id), 0.75, 3 * x + 2.75, 3 * y + 2.75)) # for i in range(inputNum): # d.append(draw.Text(str(i),3, 1.5,i*3+6-1))
self.y = random.random() * sizey self.xn = self.x self.yn = self.y def step(self): t = getnoise(self.x, self.y) * 5 * math.pi self.x = self.xn self.y = self.yn self.xn += steplenght * math.cos(t) self.yn += steplenght * math.sin(t) if self.xn < 0 or self.xn > sizex or self.yn < 0 or self.yn > sizey: return None return self.xn, self.yn, self.x, self.y canvas = drawSvg.Drawing(sizex, sizey, displayInline='False') actors = [] for a in range(actorsnum): n = Actor() actors.append(n) for s in range(stepsnum): for a in actors: p = a.step() if p: canvas.append(drawSvg.Line(p[2], p[3], p[0], p[1], stroke='black', stroke_width=1)) else: actors.remove(a) canvas.saveSvg('test.svg')
def svg( bro: BrinOverlap, outfile: Optional[str] = None, width: float = DEFAULT_WIDTH, block_height: float = DEFAULT_BLOCK_HEIGHT, num_ticks: Optional[int] = None, colormap: Optional[str] = DEFAULT_COLORMAP, ) -> draw.Drawing: full_width = width del width # avoid confusion # without margin, the bottom stroke border looks funky for some reason. full_height = block_height * len(bro.levels) + CANVAS_MARGIN * 2 d = draw.Drawing(full_width, full_height) # area for main drawing canvas_width = full_width - CANVAS_MARGIN * 2 canvas_height = full_height - CANVAS_MARGIN * 2 # draw border around block range rectangles d.append( draw.Rectangle( CANVAS_MARGIN, CANVAS_MARGIN, canvas_width, canvas_height, fill="none", stroke="black", stroke_width=2, )) def interpx(dt: datetime) -> float: val_range = bro.max_val - bro.min_val return (dt - bro.min_val) / val_range * canvas_width def xywh(br: BlockRange, num_level: int) -> tuple[float, float, float, float]: x = interpx(br.start) w = interpx(br.end) - x y = num_level * block_height h = block_height # w can be < HGAP when there are many blocks / insufficient canvas # width, so use max to ensure visibility. res = (x + CANVAS_MARGIN, y + CANVAS_MARGIN, max(2, w - HGAP), h - VGAP) # print(res) return res # draw block ranges cmap = cm.get_cmap(colormap) if colormap else None for num_level, level in enumerate(bro.levels): for br in level: p = _br_frac(br.blknum, bro.min_blknum, bro.max_blknum) color = colors.to_hex(cmap(p)) if cmap else "lightgrey" r = draw.Rectangle(*xywh(br, num_level), fill=color, stroke="black") d.append(r) # draw time ticks if num_ticks is None: datetime_range = _auto_datetime_range(bro.min_val, bro.max_val, _auto_num_ticks(canvas_width)) else: datetime_range = _even_datetime_range(bro.min_val, bro.max_val, num_ticks) prev_date = None for dt in datetime_range: # text = [] # if prev_date != dt.date(): # text.append(dt.strftime("%Y-%m-%d")) # text.append(dt.strftime("%H:%M")) text = [ "" if prev_date == dt.date() else dt.strftime("%Y-%m-%d"), dt.strftime("%H:%M"), ] prev_date = dt.date() x = interpx(dt) + CANVAS_MARGIN # y = font size because multi-line string. d.append( draw.Text(text, DATE_FONT_SIZE, x, DATE_FONT_SIZE, center=True)) d.append( draw.Line(x, CANVAS_MARGIN, x, CANVAS_MARGIN - TICK_LENGTH, stroke="black")) if outfile: print(f"saving to {outfile}") d.saveSvg(outfile) return d
def build(sides, thickness): print(sides) thickness = 5 ''' sides: the sidelengths from input, used to preserve sidelength ratios, ''' ## svg shouldnt be too big for efficiencys sake ## only needs to be cx+ 2*flaplength(=cx*0.15) ... cy = sides[0][1] cx = sides[0][0] flap = (round(0.15 * (cx / 4), 4)) ## canvas object, ''' cx+flap because it shouldnt be huge, canvas is only as large as it needs to be+ 30 px for margin ''' ##print(cx+(2*flap)+30) ##print(cy+(2*flap)+30) d = draw.Drawing(700, 700, origin='center', displayInline=False) maxX = 600 / 2 maxY = 600 / 2 linex = -flap xval = -maxX + flap + 15 ## 30 is margin.. initPos = xval - linex initNeg = xval + linex inter_pts = [] d.append( draw.Line(initNeg, -flap, initNeg, cy / 4 + (2 * flap), stroke='black')) finalPos = xval - linex finalNeg = xval + linex animIter = 1 tooth_coords = [] for s in sides: ## ratio * any width = the same rectangle proportionally ##ratio = get_side_ratio(s) #3 s = (384,649) ## print(s) w, h = s w = w / 4 h = h / 4 ## xval, 0 = BOTTOM LEFT CORNER OF RECT ## draw 4 main recs, use as a guide for building ''' d.append(draw.Rectangle(xval, 0, w, h, stroke_width=1, stroke='white', fill='red')) ''' ## add top-notches (NOT FLESHED OUT, only placeholders) ## bottom triangles d.append(draw.Line(xval, 0, initPos, -flap, stroke='black')) d.append(draw.Line(xval, 0, initNeg, -flap, stroke='black')) ## add tooth above triangle d.append( draw.Line(xval - (0.5 * thickness), h, xval - (0.5 * thickness), h + flap * 2, stroke='black')) d.append( draw.Line(xval + (0.5 * thickness), h, xval + (0.5 * thickness), h + flap * 2, stroke='black')) ## connect bottom triangles ##d.append(draw.Line(initPos,-flap,init, cy/4+(2*flap),stroke='black')) d.append( draw.Line(initPos, -flap, initPos + w - (flap * 2), -flap, stroke='black')) xval += w initPos += w initNeg += w ##print(xval) d.saveSvg('anim' + str(animIter) + '.svg') animIter += 1 ##d.append(draw.Line(initPos,-flap,initPos+w-(flap), -flap,stroke='black')) ## add far left flap topLeft = cy / 4 + (2 * flap) ##xvalOrig = -maxX + flap + 15 d.append( draw.Line(initPos - (flap * 2), -flap, initPos - (flap * 2) + flap, 0, stroke='black')) ## connect FL flap to top d.append( draw.Line(initPos - (flap * 2) + flap, 0, initNeg + flap, cy / 4 + (2 * flap), stroke='black')) ## TOP LINE, need to break up into peices d.append( draw.Line(finalNeg, topLeft, initNeg + flap, topLeft, stroke='black')) d.saveSvg('ex.svg')
def draw_img(change): dwg.children.clear() width = 173 * (levers["face_aspect_ratio"].value)**0.5 height = 173 / (levers["face_aspect_ratio"].value)**0.5 cx = 800 / 2 cy = 600 / 2 #Ears ear_angle = levers["ear_angle"].value ear_tip_angle = levers["ear_tip_angle"].value ear_length = levers["ear_length"].value ear_orientation = levers["ear_orientation"].value ear_point = levers["ear_point"].value eye_height = levers["eye_height"].value eye_width = eye_height * levers["eye_aspect_ratio"].value eye_distance = levers["eye_distance"].value nose_size = levers["nose_size"].value fur_color = "hsl(%i, %i%%, %i%%)" % ( 45, levers["fur_saturation"].value, levers["fur_lightness"].value) dist_to_tip = r_ellipse(ear_angle, width, height) + ear_length right_tip = dir_point((cx, cy), dist_to_tip, ear_angle) bottom_right = dir_point( right_tip, ear_length * 2.2, 180 + ear_angle + ear_tip_angle * ear_orientation) bottom_right_ctrl = dir_point( bottom_right, ear_length * 2.2 - ear_point, ear_angle + ear_tip_angle * ear_orientation) top_right = dir_point( right_tip, ear_length * 2.2, 180 + ear_angle - ear_tip_angle * (1 - ear_orientation)) top_right_ctrl = dir_point( top_right, ear_length * 2.2 - ear_point, ear_angle - ear_tip_angle * (1 - ear_orientation)) top_left, top_left_ctrl, left_tip, bottom_left_ctrl, bottom_left = mirror( [ top_right, top_right_ctrl, right_tip, bottom_right_ctrl, bottom_right ], cx) left_ear = draw.Path(stroke_width=1, stroke='black', fill=fur_color) left_ear.M(*bottom_left) left_ear.L(*bottom_left_ctrl) left_ear.A(ear_point * .8, ear_point * .8, 0, False, True, *top_left_ctrl) left_ear.L(*top_left) right_ear = draw.Path(stroke_width=1, stroke='black', fill=fur_color) right_ear.M(*bottom_right) right_ear.L(*bottom_right_ctrl) right_ear.A(ear_point * .8, ear_point * .8, 0, False, False, *top_right_ctrl) right_ear.L(*top_right) dwg.draw(left_ear) dwg.draw(right_ear) #Face face = ellipse(cx, cy, width, height, stroke_width=1, stroke='black', fill=fur_color) dwg.draw(face) #Eyes left_eye = ellipse(cx - eye_distance, cy + height / 4, eye_width, eye_height, stroke_width=1, stroke='black', fill="black") right_eye = ellipse(cx + eye_distance, cy + height / 4, eye_width, eye_height, stroke_width=1, stroke='black', fill="black") dwg.draw(left_eye) dwg.draw(right_eye) #Nose dwg.draw( draw.Lines(cx - nose_size, cy + nose_size / 3, cx + nose_size, cy + nose_size / 3, cx, cy - nose_size, close=True, stroke_width=1, stroke='black', fill="black")) #Snout dwg.draw( draw.Line(cx, cy - nose_size, cx, cy - nose_size * 2.5, stroke_width=2, stroke='black', fill="black")) #Mouth mouth = draw.Path(fill="none", stroke_width=2, stroke='black') mouth.M(cx - nose_size * 2, cy - nose_size * 2.5 - 4) mouth.A(nose_size * 2, nose_size * 2, 30, False, False, cx, cy - nose_size * 2.5) mouth.A(nose_size * 2, nose_size * 2, 150, False, False, cx + nose_size * 2, cy - nose_size * 2.5 - 4) dwg.draw(mouth) #Whiskers whisker_length = levers["whisker_length"].value whiskers = [((cx - 34, cy - nose_size - 10), 195), ((cx - 40, cy - nose_size - 4), 185), ((cx - 34, cy - nose_size + 2), 175), ((cx + 34, cy - nose_size - 10), 345), ((cx + 40, cy - nose_size - 4), 355), ((cx + 34, cy - nose_size + 2), 5)] for whisker in whiskers: dwg.draw( draw.Line(*whisker[0], *dir_point(whisker[0], whisker_length, whisker[1]), stroke_width=1, stroke='black', fill="black")) animal.refresh()
def draw_genes(annotations, scale, color_table): '''Draw the genes in annotations. ''' # Define the coordinate system to draw on. # x length is fixed, y depends on how many species/strains are in the # annotations (how many gff's were given to the script) y_len = 25*len(annotations) + 50 # Add 50 for the scale bar d = draw.Drawing(500, y_len, origin = (0,0), displayInline=False) for idx, (k, v) in enumerate(annotations.items()): genes, min, max = v[0], v[1], v[2] contig_length = (max - min)*scale offset = 35 row = y_len-25*(idx+1) # Draw a line for each gff file and it's name d.append(draw.Line(offset, row, contig_length+offset, row, stroke='black', stroke_width=2, fill='none')) d.append(draw.Text(k[:10],6, 2, row-1, text_anchor="left", fill='black')) for gene in genes: color = color_table[gene[4]] arrow = draw.Marker(0, -0.5, 1, 0.5, scale=2, orient='auto') arrow.append(draw.Lines(0, -0.5, 0, 0.5, 1, 0, fill=color, close=True)) # Draw genes gene_coords = ((gene[1] - min)*scale+offset, \ (gene[2] - min)*scale+offset) midpoint = int(gene_coords[0] + (gene_coords[1] - gene_coords[0]) / 2) arrow_positions = [] # Shit code but extend the arrows from the midpoint in both # directions i = midpoint while i < int(gene_coords[1])-1: arrow_positions.append(i) i += int(600*scale) i = midpoint - int(600*scale) while i > int(gene_coords[0])+1: arrow_positions.append(i) i -= int(600*scale) # To draw arrows in correct orientation k = -1 if gene[3] == "+" else 1 # Draw a line for each gene d.append(draw.Line(gene_coords[0], row, gene_coords[1], row, \ stroke=color, stroke_width=6, fill='none')) # Draw arrows on the gene, depending on orientation for a in arrow_positions: d.append(draw.Lines(a+k, row+2, a-k, row, a+k, row-2, \ stroke_width=0.2, stroke = "black",fill="none")) ## Draw labels # Gene name, skip hypothetical proteins if gene[4] != "hypothetical_protein": text_pos = gene_coords[0] + (gene_coords[1]-gene_coords[0])/2 d.append(draw.Text(gene[4],5, text_pos,row-10, center=0.6, text_anchor="middle", fill='black')) # Draw a scale bar longest = int(450 / scale) row = 25 d.append(draw.Line(offset, row, longest, row, stroke='black', stroke_width=1, fill='none')) for num in range(0,longest, 1000): scaled_num = num*scale + offset d.append(draw.Line(scaled_num, row+1.5, scaled_num, row-1.5, stroke='black', stroke_width=0.5, fill='none')) d.append(draw.Text(str(num), 3, scaled_num, row-5, center=True, fill='black')) d.setPixelScale(2) d.saveSvg('test.svg')
def draw_dash_boundary(boundary_csv, drawing): df = pd.read_csv(boundary_csv) for line in df.itertuples(): x1, y1, x2, y2 = line.x1*XY_RATIO, line.y1*XY_RATIO, line.x2*XY_RATIO, line.y2*XY_RATIO drawing.append(draw.Line(x1, y1, x2, y2, stroke='black', stroke_dasharray='2,1')) return drawing
def ImageBuilder(self, drawPath, drawHeat): """ Karte als .png bauen :bool drawHeat: Soll heat map zeichnen :bool drawPath: Soll Pfad zeichnen :return: - """ with open(self.FILE_PATH + "karte.json") as json_file: mapDict = json.load(json_file) # Kartendaten lesen dimensions = mapDict["image"]["dimensions"] floor = mapDict["image"]["pixels"]["floor"] if "dirt" in mapDict: dirt = mapDict["dirt"] obstacle_strong = mapDict["image"]["pixels"]["obstacle_strong"] no_go_areas = mapDict["forbidden_zones"] # obstacle_weak = json_file["image"]["pixels"]["segments"][31] # Roboterdaten lesen if "robot" in mapDict: robot = mapDict["robot"] if "charger" in mapDict: charger = mapDict["charger"] path = mapDict["path"]["points"] position = mapDict["image"]["position"] current_angle = mapDict["path"]["current_angle"] # Icons einlesen #d_station = self.FILE_PATH + "assets//charger.png" #SvgImage.add(d_station, {'x': 10, 'y': 20, 'width': 80, 'height': 55, 'fill': 'blue'}) #vacuum = Image.open(self.FILE_PATH + "assets//robot.png") # correct for inverse rotation #vacuum = vacuum.rotate(270 - current_angle) # Karte zeichnen svgImage = draw.Drawing(dimensions["width"] * self.SCALE_FACTOR, dimensions["height"] * self.SCALE_FACTOR, origin=(0, -dimensions["height"] * self.SCALE_FACTOR), displayInline=False) for coordinate in floor: svgImage.append(draw.Rectangle(coordinate[0] * self.SCALE_FACTOR, -coordinate[1] * self.SCALE_FACTOR, 1 * self.SCALE_FACTOR, 1 * self.SCALE_FACTOR, fill=self.COLOR_FLOOR)) for coordinate in obstacle_strong: svgImage.append(draw.Rectangle(coordinate[0] * self.SCALE_FACTOR, -coordinate[1] * self.SCALE_FACTOR, 1 * self.SCALE_FACTOR, 1 * self.SCALE_FACTOR, fill=self.COLOR_OBSTACLE_STRONG)) # Roboterpfad if drawPath and len(path) > 1: old_x = self.TransformCoords(path[0][0], position["left"]) old_y = self.TransformCoords(path[0][1], position["top"]) for i in range(len(path)): if (i == len(path) - 1): break if i % 2 == 1: continue new_x = self.TransformCoords( path[i + 1][0], position["left"]) new_y = self.TransformCoords( path[i + 1][1], position["top"]) svgImage.append(draw.Line(old_x, -old_y, new_x, -new_y, stroke=self.COLOR_PATH, stroke_width=0.25 * self.SCALE_FACTOR, fill='none')) old_x = new_x old_y = new_y # Icons zeichnen # if "charger" in mapDict: # # Herunterskalieren # d_station.thumbnail( # (8 * self.SCALE_FACTOR, 8 * self.SCALE_FACTOR), Image.ANTIALIAS) # SvgImage.paste(d_station, # ( self.TransformCoords(charger[0], position["left"]) - round(d_station.width / 2), # self.TransformCoords(charger[1], position["top"]) - round(d_station.height / 2)), # d_station) # if "robot" in mapDict: # # Herunterskalieren # vacuum.thumbnail((8 * self.SCALE_FACTOR, 8 * # self.SCALE_FACTOR), Image.ANTIALIAS) # SvgImage.paste(vacuum, # ( self.TransformCoords(robot[0], position["left"]) - round(vacuum.width / 2), # self.TransformCoords(robot[1], position["top"]) - round(vacuum.height / 2)), # vacuum) # Schmutzpunkte zeichen if "dirt" in mapDict: for spot in dirt: svgImage.append(draw.Rectangle(self.TransformCoords(spot[0][0], position["left"]), self.TransformCoords(spot[0][0], position["top"]), 1 * self.SCALE_FACTOR, 1 * self.SCALE_FACTOR, fill=self.HueToRGB(spot[1]))) svgImage.setRenderSize(dimensions["width"] * self.SCALE_FACTOR, dimensions["height"] * self.SCALE_FACTOR) # Karte speichern svgImage.saveSvg(self.FILE_PATH + "karte.svg")
def render_line(line, model, target, style=None): style = style_join(style or {}, line.style) assert len(style) > 0 x1, y1 = N(model[line.pt1.x]), M(model[line.pt1.y], target) x2, y2 = N(model[line.pt2.x]), M(model[line.pt2.y], target) target.append(draw.Line(x1, y1, x2, y2, **style))
def drawPin( self, d, pinName, pinNumber, x1, y1, pin_name_offset, length=0, orientation="R", pen=5, text_size=50, shape_of_pin="", ): # if shape_of_pin starts with 'N' then its invisible if len(shape_of_pin) > 0 and shape_of_pin[0] == 'N': pass # C 55 0 10 1 0 6 N ->invertec pin circle shape example. else: x1 = int(x1) y1 = int(y1) text_size = int(text_size) length = int(length) pin_name_offset = int(pin_name_offset) pen = int(pen) v_list = [(x1, y1)] self.update_svg_boundary(v_list) if orientation == "R": x2 = x1 + length y2 = y1 # draw pin shape # subtracted 12 just to make the pin look better shape_x = x2 - self.RADIUS_OF_NOT_GATE shape_y = y2 # to position pin number properly x = x1 + (length / 2) y = y1 + self.PIN_NUMBER_OFFSET # x = x1 d.append( draw.Text(pinNumber, text_size / self.TEXT_SIZE_REDUCE_RATION, x, y, center=0.6, fill=self.PIN_NUMBER_COLOR)) d = self.draw_pin_shape(d, shape_x, shape_y, x2, y2, orientation, shape_of_pin) if pinName != "~": d = self.draw_text( d, pinName, x1 + length + pin_name_offset, y1, text_size, fill=self.PIN_NAME_COLOR, ) # d.append(draw.Text(pinName,text_size,x1+length+pin_name_offset,y1,center=0.6,fill=self.PIN_NAME_COLOR)) elif orientation == "L": x2 = x1 - length y2 = y1 # draw pin shape # added 12 just to make the pin look better shape_x = x2 + self.RADIUS_OF_NOT_GATE shape_y = y2 # to position pin number properly x = x1 - (length / 2) # y = y1 + 30 y = y1 + self.PIN_NUMBER_OFFSET # x = x1 d.append( draw.Text(pinNumber, text_size / self.TEXT_SIZE_REDUCE_RATION, x, y, center=0.6, fill=self.PIN_NUMBER_COLOR)) d = self.draw_pin_shape(d, shape_x, shape_y, x2, y2, orientation, shape_of_pin) if pinName != "~": d = self.draw_text( d, pinName, x1 - length - pin_name_offset, y1, text_size, fill=self.PIN_NAME_COLOR, ) # d.append(draw.Text(pinName,text_size,x1-length-pin_name_offset,y1,center=0.6,fill=self.PIN_NAME_COLOR)) elif orientation == "U": x2 = x1 y2 = y1 + length # draw pin shape # draw pin shape shape_x = x2 shape_y = y2 - self.RADIUS_OF_NOT_GATE d = self.draw_pin_shape(d, shape_x, shape_y, x2, y2, orientation, shape_of_pin) # to position pin number properly # x = x1 - 50 x = x1 - self.PIN_NUMBER_OFFSET y = y2 - (length / 3) # y = y1 d.append( draw.Text(pinNumber, text_size / self.TEXT_SIZE_REDUCE_RATION, x, y, center=0.6, fill=self.PIN_NUMBER_COLOR)) d = self.draw_pin_shape(d, x2, y2, x2, y2, orientation, shape_of_pin) if pinName != "~": d = self.draw_text( d, pinName, x1, y1 + length + pin_name_offset, text_size, fill=self.PIN_NAME_COLOR, ) # d.append(draw.Text(pinName,text_size,x1,y1+length+pin_name_offset,center=0.6,fill=self.PIN_NAME_COLOR)) else: x2 = x1 y2 = y1 - length # draw pin shape # d = self.draw_pin_shape(d, x2, y2, orientation, shape_of_pin) # draw pin shape # subtracted 12 just to make the pin look better shape_x = x2 shape_y = y2 + self.RADIUS_OF_NOT_GATE # y2 = y1 # to position pin number properly # x = x1 - 40 x = x1 - self.PIN_NUMBER_OFFSET # x = x1 - 20 y = y2 + (length / 3) d.append( draw.Text(pinNumber, text_size / self.TEXT_SIZE_REDUCE_RATION, x, y, center=0.6, fill=self.PIN_NUMBER_COLOR)) d = self.draw_pin_shape(d, shape_x, shape_y, x2, y2, orientation, shape_of_pin) if pinName != "~": d = self.draw_text( d, pinName, x1, y1 - length - pin_name_offset, text_size, fill=self.PIN_NAME_COLOR, ) # d.append(draw.Text(pinName,text_size,x1,y1-length-pin_name_offset,center=0.6,fill=self.PIN_NAME_COLOR)) d.append( draw.Line(x1, y1, x2, y2, stroke=self.STROKE_COLOR, stroke_width=pen)) return d
if shape.shape_type == MSO_SHAPE_TYPE.AUTO_SHAPE: if shape.auto_shape_type == MSO_SHAPE.OVAL: r = shape.width/FACTOR c = shape.fill.fore_color.rgb line_color = shape.line.fill.fore_color.rgb line_width = shape.line.width/FACTOR g.append(draw.Circle(shape.left/FACTOR+r/2, shape.top/FACTOR+r/2, r/2, fill='#{}'.format(c), stroke='#{}'.format(line_color), stroke_width=line_width)) elif shape.shape_type == MSO_SHAPE_TYPE.GROUP: print(shape, shape.name, "SHAPE len = {}".format(len(shape.shapes))) for shape in shape.shapes: print(shape.shape_type, shape.left, shape.top, shape.width, shape.height) g.append(draw.Rectangle(shape.left/FACTOR, shape.top/FACTOR, shape.width/FACTOR, shape.height/FACTOR, fill='#1248ff')) elif shape.shape_type == MSO_SHAPE_TYPE.LINE: line_color = shape.line.fill.fore_color.rgb line_width = shape.line.width/FACTOR g.append(draw.Line(shape.begin_x/FACTOR, shape.begin_y/FACTOR, shape.end_x/FACTOR, shape.end_y/FACTOR, stroke='#{}'.format(line_color), stroke_width=line_width)) elif shape.shape_type == MSO_SHAPE_TYPE.PLACEHOLDER: print(shape.text) g.append(draw.Rectangle(shape.left/FACTOR, shape.top/FACTOR, shape.width/FACTOR, shape.height/FACTOR, fill='none', stroke='#1248ff', stroke_width=1000/FACTOR)) g.append(draw.Text(shape.text, 400, 0, -400, text_anchor='start', transform='scale(1,-1) translate({},{})'.format(shape.left/FACTOR, shape.top/FACTOR))) elif shape.shape_type == MSO_SHAPE_TYPE.PICTURE: g.append(draw.Image(shape.left/FACTOR, shape.top/FACTOR, shape.width/FACTOR, shape.height/FACTOR, data=shape.image.blob)) else: g.append(draw.Rectangle(shape.left/FACTOR, shape.top/FACTOR, shape.width/FACTOR, shape.height/FACTOR, fill='#1248ff')) # d.append(draw.Rectangle(shape.left/FACTOR, pres.slide_height/FACTOR-shape.top/FACTOR, shape.width/FACTOR, shape.height/FACTOR, fill='#1248ff')) # g.append(draw.Text('Text at (2,1)',0.5, 0,0, text_anchor='middle', transform='scale(1,-1) translate(2,1)')) d.append(g) d.setRenderSize(h=600) d.saveSvg('out.svg')