本文整理汇总了Python中simpletransform.applyTransformToPath函数的典型用法代码示例。如果您正苦于以下问题:Python applyTransformToPath函数的具体用法?Python applyTransformToPath怎么用?Python applyTransformToPath使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了applyTransformToPath函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plotPath
def plotPath(self, node, matTransform):
""" Plot the path while applying the transformation defined by the matrix matTransform. """
filledPath = (simplestyle.parseStyle(node.get("style")).get("fill", "none") != "none")
# Plan: Turn this path into a cubicsuperpath (list of beziers)...
d = node.get("d")
if len(simplepath.parsePath(d)) == 0:
return
p = cubicsuperpath.parsePath(d)
# ... and apply the transformation to each point.
simpletransform.applyTransformToPath(matTransform, p)
# p is now a list of lists of cubic beziers [cp1, cp2, endp]
# where the start-point is the last point of the previous segment.
# For some reason the inkscape extensions uses csp[1] as the coordinates of each point,
# but that makes it seem like they are using control point 2 as line points.
# Maybe that is a side-effect of the CSP subdivion process? TODO
realPoints = []
for sp in p:
cspsubdiv.subdiv(sp, self.smoothness)
for csp in sp:
realPoints.append( (csp[1][0], csp[1][1]) )
self.rawObjects.append( (filledPath, realPoints) )
示例2: recursiveFuseTransform
def recursiveFuseTransform(self, node, transf=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]):
transf = composeTransform(transf, parseTransform(node.get("transform", None)))
if 'transform' in node.attrib:
del node.attrib['transform']
if 'style' in node.attrib:
style = node.attrib.get('style')
style = simplestyle.parseStyle(style)
update = False
if 'stroke-width' in style:
try:
stroke_width = self.unittouu(style.get('stroke-width').strip())
# pixelsnap ext assumes scaling is similar in x and y
# and uses the x scale...
# let's try to be a bit smarter
stroke_width *= math.sqrt(transf[0][0]**2 + transf[1][1]**2)
style['stroke-width'] = str(stroke_width)
update = True
except AttributeError:
pass
if update:
style = simplestyle.formatStyle(style)
node.attrib['style'] = style
node = ApplyTransform.objectToPath(node)
if 'd' in node.attrib:
d = node.get('d')
p = cubicsuperpath.parsePath(d)
applyTransformToPath(transf, p)
node.set('d', cubicsuperpath.formatPath(p))
elif node.tag in [inkex.addNS('polygon', 'svg'),
inkex.addNS('polyline', 'svg')]:
points = node.get('points')
points = points.strip().split(' ')
for k,p in enumerate(points):
if ',' in p:
p = p.split(',')
p = [float(p[0]),float(p[1])]
applyTransformToPoint(transf, p)
p = [str(p[0]),str(p[1])]
p = ','.join(p)
points[k] = p
points = ' '.join(points)
node.set('points', points)
elif node.tag in [inkex.addNS('rect', 'svg'),
inkex.addNS('text', 'svg'),
inkex.addNS('image', 'svg'),
inkex.addNS('use', 'svg')]:
node.set('transform', formatTransform(transf))
for child in node.getchildren():
self.recursiveFuseTransform(child, transf)
示例3: effect
def effect(self):
if len(self.options.ids) < 2:
inkex.errormsg(_("This extension requires two selected paths. \nThe second path must be exactly four nodes long."))
exit()
#obj is selected second
scale = self.unittouu('1px') # convert to document units
obj = self.selected[self.options.ids[0]]
trafo = self.selected[self.options.ids[1]]
if obj.get(inkex.addNS('type','sodipodi')):
inkex.errormsg(_("The first selected object is of type '%s'.\nTry using the procedure Path->Object to Path." % obj.get(inkex.addNS('type','sodipodi'))))
exit()
if obj.tag == inkex.addNS('path','svg') or obj.tag == inkex.addNS('g','svg'):
if trafo.tag == inkex.addNS('path','svg'):
#distil trafo into four node points
mat = simpletransform.composeParents(trafo, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
trafo = cubicsuperpath.parsePath(trafo.get('d'))
if len(trafo[0]) < 4:
inkex.errormsg(_("This extension requires that the second selected path be four nodes long."))
exit()
simpletransform.applyTransformToPath(mat, trafo)
trafo = [[Point(csp[1][0],csp[1][1]) for csp in subs] for subs in trafo][0][:4]
#vectors pointing away from the trafo origin
self.t1 = Segment(trafo[0],trafo[1])
self.t2 = Segment(trafo[1],trafo[2])
self.t3 = Segment(trafo[3],trafo[2])
self.t4 = Segment(trafo[0],trafo[3])
#query inkscape about the bounding box of obj
self.q = {'x':0,'y':0,'width':0,'height':0}
file = self.args[-1]
id = self.options.ids[0]
for query in self.q.keys():
if bsubprocess:
p = Popen('inkscape --query-%s --query-id=%s "%s"' % (query,id,file), shell=True, stdout=PIPE, stderr=PIPE)
rc = p.wait()
self.q[query] = scale*float(p.stdout.read())
err = p.stderr.read()
else:
f,err = os.popen3('inkscape --query-%s --query-id=%s "%s"' % (query,id,file))[1:]
self.q[query] = scale*float(f.read())
f.close()
err.close()
if obj.tag == inkex.addNS("path",'svg'):
self.process_path(obj)
if obj.tag == inkex.addNS("g",'svg'):
self.process_group(obj)
else:
if trafo.tag == inkex.addNS('g','svg'):
inkex.errormsg(_("The second selected object is a group, not a path.\nTry using the procedure Object->Ungroup."))
else:
inkex.errormsg(_("The second selected object is not a path.\nTry using the procedure Path->Object to Path."))
exit()
else:
inkex.errormsg(_("The first selected object is not a path.\nTry using the procedure Path->Object to Path."))
exit()
示例4: effect
def effect(self):
""" This method is called first, and sets up the self.commands list for later output. """
svg = self.document.getroot()
# find document width and height, used to scale down
self.doc_width = inkex.unittouu(svg.get('width'))
self.doc_height = inkex.unittouu(svg.get('height'))
# add header
self.commands.append("^DF;")
self.commands.append("! 1;")
self.commands.append("H;")
self.commands.append("@ %d %d;" % (self.options.z_down, self.options.z_up))
self.commands.append("V {0};F {0};\n".format(self.options.feed_rate_moving))
self.commands.append("Z 0 0 %d;" % self.options.z_up)
# mostly borrowed from hgpl_output.py
lastX = 0
lastY = 0
# find paths in layers
i = 0
layerPath = '//svg:g[@inkscape:groupmode="layer"]'
for layer in svg.xpath(layerPath, namespaces=inkex.NSS):
i += 1
nodePath = ('//svg:g[@inkscape:groupmode="layer"][%d]/descendant::svg:path') % i
for node in svg.xpath(nodePath, namespaces=inkex.NSS):
# these next lines added from this patch to fix the transformation issues - http://launchpadlibrarian.net/36269154/hpgl_output.py.patch
# possibly also want to try this code: https://bugs.launchpad.net/inkscape/+bug/600472/+attachment/1475310/+files/hpgl_output.py
transforms = node.xpath("./ancestor-or-self::svg:*[@transform]",namespaces=inkex.NSS)
matrix = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
for parenttransform in transforms:
newmatrix = simpletransform.parseTransform(parenttransform.get("transform"))
matrix = simpletransform.composeTransform(matrix, newmatrix)
d = node.get('d')
if len(simplepath.parsePath(d)):
p = cubicsuperpath.parsePath(d)
simpletransform.applyTransformToPath(matrix, p) # this line is also from the transform-fixing patch mentioned above
cspsubdiv.cspsubdiv(p, self.options.flat)
for sp in p:
first = True
for csp in sp:
if first:
x, y = self.conv_coords(csp[1][0], self.doc_height - csp[1][1])
self.commands.append("Z %d %d %d;" % (x, y, self.options.z_up))
self.commands.append("V {0};F {0};".format(self.options.feed_rate_cutting))
first = False
x, y = self.conv_coords(csp[1][0], self.doc_height - csp[1][1])
self.commands.append("Z %d %d %d;" % (x, y, self.options.z_down))
lastX = x
lastY = y
self.commands.append("V {0};F {0};".format(self.options.feed_rate_moving))
self.commands.append("Z %d %d %d;" % (lastX, lastY, self.options.z_up))
self.commands.append("Z 0 0 %d;" % self.options.z_up)
self.commands.append("H;")
示例5: effect
def effect(self):
paths = []
for id, node in self.selected.iteritems():
if node.tag == '{http://www.w3.org/2000/svg}path':
paths.append(node)
if len(paths) == 2:
break
else:
sys.stderr.write('Need 2 paths selected\n')
return
pts = [cubicsuperpath.parsePath(paths[i].get('d'))
for i in (0,1)]
for i in (0,1):
if 'transform' in paths[i].keys():
trans = paths[i].get('transform')
trans = simpletransform.parseTransform(trans)
simpletransform.applyTransformToPath(trans, pts[i])
verts = []
for i in range(0, min(map(len, pts))):
comp = []
for j in range(0, min(len(pts[0][i]), len(pts[1][i]))):
comp.append([pts[0][i][j][1][-2:], pts[1][i][j][1][-2:]])
verts.append(comp)
if self.options.mode.lower() == 'lines':
line = []
for comp in verts:
for n,v in enumerate(comp):
line += [('M', v[0])]
line += [('L', v[1])]
ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path')
paths[0].xpath('..')[0].append(ele)
ele.set('d', simplepath.formatPath(line))
ele.set('style', 'fill:none;stroke:#000000;stroke-opacity:1;stroke-width:1;')
elif self.options.mode.lower() == 'polygons':
g = inkex.etree.Element('{http://www.w3.org/2000/svg}g')
g.set('style', 'fill:#000000;stroke:#000000;fill-opacity:0.3;stroke-width:2;stroke-opacity:0.6;')
paths[0].xpath('..')[0].append(g)
for comp in verts:
for n,v in enumerate(comp):
nn = n+1
if nn == len(comp): nn = 0
line = []
line += [('M', comp[n][0])]
line += [('L', comp[n][1])]
line += [('L', comp[nn][1])]
line += [('L', comp[nn][0])]
line += [('L', comp[n][0])]
ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path')
g.append(ele)
ele.set('d', simplepath.formatPath(line))
示例6: load
def load(self, node, mat):
self.id = node.get('id')
d = node.get('d')
if len(simplepath.parsePath(d)) == 0:
return
p = cubicsuperpath.parsePath(d)
applyTransformToPath(mat, p)
# p is now a list of lists of cubic beziers [ctrl p1, ctrl p2, endpoint]
# where the start-point is the last point in the previous segment
self.points = []
self.paths = []
for sp in p:
path = []
subdivide_cubic_path(sp, 0.2) # TODO: smoothness preference
for csp in sp:
point = [csp[1][0], csp[1][1]]
if point not in self.points:
self.points.append(point)
path.append(self.points.index(point))
self.paths.append(path)
# get color
style = node.get('style')
try:
hexcolor = re.search('fill:#([0-9a-fA-f]{6})', style).group(1)
rgb = [
int(hexcolor[0:2], 16),
int(hexcolor[2:4], 16),
int(hexcolor[4:6], 16)
]
except (TypeError, AttributeError):
rgb = None
# get optional opacity
try:
opacity = float(re.search('(?:^|;)opacity:([0-9]*\.?[0-9]+)', style).group(1))
except (TypeError, AttributeError):
opacity = 1.0
# get optional fill-opacity (of course there is more than one way to set opacity of paths...)
try:
fill_opacity = float(re.search('(?:^|;)fill-opacity:([0-9]*\.?[0-9]+)', style).group(1))
except (TypeError, AttributeError):
fill_opacity = 1.0
if rgb:
self.color = [
rgb[0] / 255.0,
rgb[1] / 255.0,
rgb[2] / 255.0,
opacity * fill_opacity
]
else:
self.color = None
示例7: effect
def effect(self):
for id, node in self.selected.iteritems():
if node.tag == '{http://www.w3.org/2000/svg}path':
path=node
break
else:
sys.stderr.write('Need one path selected\n')
return
pts = cubicsuperpath.parsePath(path.get('d'))
if 'transform' in path.keys():
trans = path.get('transform')
trans = simpletransform.parseTransform(trans)
simpletransform.applyTransformToPath(trans, pts[i])
gtext = inkex.etree.SubElement(path.xpath('..')[0], inkex.addNS('g','svg'), {} )
gdots = inkex.etree.SubElement(path.xpath('..')[0], inkex.addNS('g','svg'), {} )
size = 10
if 'style' in path.attrib:
style=path.get('style')
if style!='':
styles=style.split(';')
for i in range(len(styles)):
if styles[i].startswith('stroke-width'):
if ( styles[i].endswith('px') or styles[i].endswith('cm') ) :
size=float(styles[i][len('stroke-width:'):-2])*2
else:
size=float(styles[i][len('stroke-width:'):])*2
# if len(pts[0])>2:
# size = math.sqrt(math.pow(pts[0][0][0][0]-pts[0][1][0][0],2)+math.pow(pts[0][0][0][1]-pts[0][1][0][1],2))/10
it = 0
for sub in pts:
for p in sub:
if it == 0:
style = { 'stroke': 'none', 'fill': 'black' }
x0 = p[0][0]
y0 = p[0][1]
circ_attribs = {'id':'pt0','style':simplestyle.formatStyle(style),'cx':str(x0), 'cy':str(y0),'r':str(size)}
circle = inkex.etree.SubElement(gdots, inkex.addNS('circle','svg'), circ_attribs )
else:
clone_attribs = { 'x':'0', 'y':'0', 'transform':'translate(%f,%f)' % (p[0][0]-x0,p[0][1]-y0) }
clone = inkex.etree.SubElement(gdots, inkex.addNS('use','svg'), clone_attribs )
xlink = inkex.addNS('href','xlink')
clone.set(xlink, '#pt0')
text_style = { 'font-size':'%dpx' % (size*2.4), 'fill':'black', 'font-family':'DejaVu Sans', 'text-anchor':'middle' }
text_attribs = { 'x':str(p[0][0]), 'y':str(p[0][1]-size*1.8), 'style':simplestyle.formatStyle(text_style) }
text = inkex.etree.SubElement(gtext, inkex.addNS('text','svg'), text_attribs)
tspan = inkex.etree.SubElement(text , 'tspan', {inkex.addNS('role','sodipodi'): 'line'})
tspan.text = '%d' % ( it+1 )
it+=1
示例8: effect
def effect(self):
paths = []
for id, node in self.selected.iteritems():
if node.tag == "{http://www.w3.org/2000/svg}path":
paths.append(node)
if len(paths) == 2:
break
else:
sys.stderr.write("Need 2 paths selected\n")
return
pts = [cubicsuperpath.parsePath(paths[i].get("d")) for i in (0, 1)]
for i in (0, 1):
if "transform" in paths[i].keys():
trans = paths[i].get("transform")
trans = simpletransform.parseTransform(trans)
simpletransform.applyTransformToPath(trans, pts[i])
verts = []
for i in range(0, min(map(len, pts))):
comp = []
for j in range(0, min(len(pts[0][i]), len(pts[1][i]))):
comp.append([pts[0][i][j][1][-2:], pts[1][i][j][1][-2:]])
verts.append(comp)
if self.options.mode.lower() == "lines":
line = []
for comp in verts:
for n, v in enumerate(comp):
line += [("M", v[0])]
line += [("L", v[1])]
ele = inkex.etree.Element("{http://www.w3.org/2000/svg}path")
paths[0].xpath("..")[0].append(ele)
ele.set("d", simplepath.formatPath(line))
ele.set("style", "fill:none;stroke:#000000;stroke-opacity:1;stroke-width:1;")
elif self.options.mode.lower() == "polygons":
g = inkex.etree.Element("{http://www.w3.org/2000/svg}g")
g.set("style", "fill:#000000;stroke:#000000;fill-opacity:0.3;stroke-width:2;stroke-opacity:0.6;")
paths[0].xpath("..")[0].append(g)
for comp in verts:
for n, v in enumerate(comp):
nn = n + 1
if nn == len(comp):
nn = 0
line = []
line += [("M", comp[n][0])]
line += [("L", comp[n][1])]
line += [("L", comp[nn][1])]
line += [("L", comp[nn][0])]
line += [("L", comp[n][0])]
ele = inkex.etree.Element("{http://www.w3.org/2000/svg}path")
g.append(ele)
ele.set("d", simplepath.formatPath(line))
示例9: process_shape
def process_shape(self, node, mat):
rgb = (0,0,0) # stroke color
fillcolor = None # fill color
stroke = 1 # pen width in printer pixels
# Very NB : If the pen width is greater than 1 then the output will Not be a vector output !
style = node.get('style')
if style:
style = simplestyle.parseStyle(style)
if style.has_key('stroke'):
if style['stroke'] and style['stroke'] != 'none' and style['stroke'][0:3] != 'url':
rgb = simplestyle.parseColor(style['stroke'])
if style.has_key('stroke-width'):
stroke = self.unittouu(style['stroke-width'])
stroke = int(stroke*self.scale)
if style.has_key('fill'):
if style['fill'] and style['fill'] != 'none' and style['fill'][0:3] != 'url':
fill = simplestyle.parseColor(style['fill'])
fillcolor = fill[0] + 256*fill[1] + 256*256*fill[2]
color = rgb[0] + 256*rgb[1] + 256*256*rgb[2]
if node.tag == inkex.addNS('path','svg'):
d = node.get('d')
if not d:
return
p = cubicsuperpath.parsePath(d)
elif node.tag == inkex.addNS('rect','svg'):
x = float(node.get('x'))
y = float(node.get('y'))
width = float(node.get('width'))
height = float(node.get('height'))
p = [[[x, y],[x, y],[x, y]]]
p.append([[x + width, y],[x + width, y],[x + width, y]])
p.append([[x + width, y + height],[x + width, y + height],[x + width, y + height]])
p.append([[x, y + height],[x, y + height],[x, y + height]])
p.append([[x, y],[x, y],[x, y]])
p = [p]
else:
return
trans = node.get('transform')
if trans:
mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
simpletransform.applyTransformToPath(mat, p)
hPen = mygdi.CreatePen(0, stroke, color)
mygdi.SelectObject(self.hDC, hPen)
self.emit_path(p)
if fillcolor is not None:
brush = LOGBRUSH(0, fillcolor, 0)
hBrush = mygdi.CreateBrushIndirect(addressof(brush))
mygdi.SelectObject(self.hDC, hBrush)
mygdi.BeginPath(self.hDC)
self.emit_path(p)
mygdi.EndPath(self.hDC)
mygdi.FillPath(self.hDC)
return
示例10: process_shape
def process_shape(self, node, mat):
rgb = (0,0,0)
style = node.get('style')
if style:
style = simplestyle.parseStyle(style)
if style.has_key('stroke'):
if style['stroke'] and style['stroke'] != 'none' and style['stroke'][0:3] != 'url':
rgb = simplestyle.parseColor(style['stroke'])
hsl = coloreffect.ColorEffect.rgb_to_hsl(coloreffect.ColorEffect(),rgb[0]/255.0,rgb[1]/255.0,rgb[2]/255.0)
self.closed = 0 # only for LWPOLYLINE
self.color = 7 # default is black
if hsl[2]:
#self.color = 1 + (int(6*hsl[0] + 0.5) % 6) # use 6 hues
self.color = 1 + (int(10*hsl[0] + 0.5) % 10) # use 6 hues
if node.tag == inkex.addNS('path','svg'):
d = node.get('d')
if not d:
return
if (d[-1] == 'z' or d[-1] == 'Z'):
self.closed = 1
p = cubicsuperpath.parsePath(d)
elif node.tag == inkex.addNS('rect','svg'):
self.closed = 1
x = float(node.get('x'))
y = float(node.get('y'))
width = float(node.get('width'))
height = float(node.get('height'))
p = [[[x, y],[x, y],[x, y]]]
p.append([[x + width, y],[x + width, y],[x + width, y]])
p.append([[x + width, y + height],[x + width, y + height],[x + width, y + height]])
p.append([[x, y + height],[x, y + height],[x, y + height]])
p.append([[x, y],[x, y],[x, y]])
p = [p]
else:
return
trans = node.get('transform')
if trans:
mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
simpletransform.applyTransformToPath(mat, p)
for sub in p:
for i in range(len(sub)-1):
s = sub[i]
e = sub[i+1]
if s[1] == s[2] and e[0] == e[1]:
if (self.options.POLY == 'true'):
self.LWPOLY_line([s[1],e[1]])
else:
self.dxf_line([s[1],e[1]])
elif (self.options.ROBO == 'true'):
self.ROBO_spline([s[1],s[2],e[0],e[1]])
else:
self.dxf_spline([s[1],s[2],e[0],e[1]])
示例11: process_path
def process_path(self,path):
mat = simpletransform.composeParents(path, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
d = path.get('d')
p = cubicsuperpath.parsePath(d)
simpletransform.applyTransformToPath(mat, p)
for subs in p:
for csp in subs:
csp[0] = self.trafopoint(csp[0])
csp[1] = self.trafopoint(csp[1])
csp[2] = self.trafopoint(csp[2])
mat = simpletransform.invertTransform(mat)
simpletransform.applyTransformToPath(mat, p)
path.set('d',cubicsuperpath.formatPath(p))
示例12: processPaths
def processPaths(self, transformMatrix):
path = '//svg:path'
pm = pathmodifier.PathModifier()
for node in self.document.getroot().xpath(path, namespaces=inkex.NSS):
pm.objectToPath(node, True)
d = node.get('d')
p = cubicsuperpath.parsePath(d)
t = node.get('transform')
if t is not None:
transformMatrix = composeTransform(transformMatrix, parseTransform(t))
applyTransformToPath(transformMatrix, p)
yield [p, node]
示例13: process_path
def process_path(self, node, mat):
d = node.get('d')
if d:
p = cubicsuperpath.parsePath(d)
trans = node.get('transform')
if trans:
mat = simpletransform.composeTransform(mat, simpletransform.parseTransform(trans))
simpletransform.applyTransformToPath(mat, p)
cspsubdiv.cspsubdiv(p, self.options.flat)
for sp in p:
first = True
for csp in sp:
cmd = 'PD'
if first:
cmd = 'PU'
first = False
self.hpgl.append('%s%d,%d;' % (cmd,csp[1][0],csp[1][1]))
示例14: process_shapes
def process_shapes(self, shapelist, transform):
"""Convert the SVG shape elements to Lines and CubicBeziers,
and apply object/layer transforms.
Returns a list of tuples ((path-id, path), ...).
"""
cutpath_list = []
for node, layer_transform in shapelist:
# Convert the shape element to a simplepath
path = supereffect.convert_element_to_path(node)
# Convert the simplepath to a 'cubicsuperpath' which is
# just a list of cubic bezier curves.
# This seems to be how most Inkscape plugins do things...
# TODO: This is really an unnecessary step since
# we could deal with SVG shapes directly...
csp = cubicsuperpath.CubicSuperPath(path)
# Apply the SVG element transform and it's layer transform to the
# path segments so that we are working in absolute coordinates.
# Transform SVG coordinates into cartesian (ie G code) coordinates
# (flip the Y axis from upper left to lower left).
# node_transform = simpletransform.parseTransform(node.get('transform'))
# node_transform = simpletransform.composeTransform(node_transform, transform)
# node_transform = simpletransform.composeTransform(node_transform, layer_transform)
node_transform = simpletransform.composeTransform(transform, layer_transform)
simpletransform.applyTransformToPath(node_transform, csp)
# Convert cubic path segments to curves and lines
# TODO: get bounding boxes and calculate offset if doc origin not used.
cutpath = paths.Path(name=node.get('id'))
for subcsp in csp:
for i in range(1,len(subcsp)):
p1 = geom.P(subcsp[i-1][1])
c1 = geom.P(subcsp[i-1][2])
p2 = geom.P(subcsp[i][0])
c2 = geom.P(subcsp[i][1])
if p1 == c1 and p2 == c2:
segment = geom.Line(p1, p2)
else:
segment = geom.CubicBezier(p1, c1, p2, c2)
cutpath.append(segment)
cutpath_list.append(cutpath)
return cutpath_list
示例15: effect
def effect(self):
# get number of digits
prec = int(self.options.precision)
scale = self.unittouu('1px') # convert to document units
self.options.offset *= scale
factor = 1.0
doc = self.document.getroot()
if doc.get('viewBox'):
[viewx, viewy, vieww, viewh] = doc.get('viewBox').split(' ')
factor = self.unittouu(doc.get('width'))/float(vieww)
if self.unittouu(doc.get('height'))/float(viewh) < factor:
factor = self.unittouu(doc.get('height'))/float(viewh)
factor /= self.unittouu('1px')
self.options.fontsize /= factor
# loop over all selected paths
for id, node in self.selected.iteritems():
if node.tag == inkex.addNS('path','svg'):
mat = simpletransform.composeParents(node, [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
p = cubicsuperpath.parsePath(node.get('d'))
simpletransform.applyTransformToPath(mat, p)
factor *= scale/self.unittouu('1'+self.options.unit)
if self.options.type == "length":
slengths, stotal = csplength(p)
self.group = inkex.etree.SubElement(node.getparent(),inkex.addNS('text','svg'))
elif self.options.type == "area":
stotal = csparea(p)*factor*self.options.scale
self.group = inkex.etree.SubElement(node.getparent(),inkex.addNS('text','svg'))
else:
xc, yc = cspcofm(p)
self.group = inkex.etree.SubElement(node.getparent(),inkex.addNS('path','svg'))
self.group.set('id', 'MassCenter_' + node.get('id'))
self.addCross(self.group, xc, yc, scale)
continue
# Format the length as string
lenstr = locale.format("%(len)25."+str(prec)+"f",{'len':round(stotal*factor*self.options.scale,prec)}).strip()
if self.options.format == 'textonpath':
if self.options.type == "length":
self.addTextOnPath(self.group, 0, 0, lenstr+' '+self.options.unit, id, 'start', '50%', self.options.offset)
else:
self.addTextOnPath(self.group, 0, 0, lenstr+' '+self.options.unit+'^2', id, 'start', '0%', self.options.offset)
else:
if self.options.type == "length":
self.addTextWithTspan(self.group, p[0][0][1][0], p[0][0][1][1], lenstr+' '+self.options.unit, id, 'start', -int(self.options.angle), self.options.offset + self.options.fontsize/2)
else:
self.addTextWithTspan(self.group, p[0][0][1][0], p[0][0][1][1], lenstr+' '+self.options.unit+'^2', id, 'start', -int(self.options.angle), -self.options.offset + self.options.fontsize/2)