本文整理汇总了Python中simplepath.parsePath函数的典型用法代码示例。如果您正苦于以下问题:Python parsePath函数的具体用法?Python parsePath怎么用?Python parsePath使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parsePath函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: effect
def effect(self):
clippingLineSegments = None
pathTag = inkex.addNS('path','svg')
groupTag = inkex.addNS('g','svg')
error_messages = []
for id in self.options.ids: # the selection, top-down
node = self.selected[id]
if node.tag == pathTag:
if clippingLineSegments is None: # first path is the clipper
(clippingLineSegments, errors) = self.simplepathToLineSegments(simplepath.parsePath(node.get('d')))
error_messages.extend(['{}: {}'.format(id, err) for err in errors])
else:
# do all the work!
segmentsToClip, errors = self.simplepathToLineSegments(simplepath.parsePath(node.get('d')))
error_messages.extend(['{}: {}'.format(id, err) for err in errors])
clippedSegments = self.clipLineSegments(segmentsToClip, clippingLineSegments)
if len(clippedSegments) != 0:
# replace the path
node.set('d', simplepath.formatPath(self.linesgmentsToSimplePath(clippedSegments)))
else:
# don't put back an empty path(?) could perhaps put move, move?
inkex.debug('Object {} clipped to nothing, will not be updated.'.format(node.get('id')))
elif node.tag == groupTag: # we don't look inside groups for paths
inkex.debug('Group object {} will be ignored. Please ungroup before running the script.'.format(id))
else: # something else
inkex.debug('Object {} is not of type path ({}), and will be ignored. Current type "{}".'.format(id, pathTag, node.tag))
for error in error_messages:
inkex.debug(error)
示例2: movePath
def movePath(self, node, x, y, origin):
tagName = self.getTagName(node)
if tagName != "path":
inkex.debug('movePath only works on SVG Path elements. Argument was of type "' + tagName + '"')
return False
path = simplepath.parsePath(node.get("d"))
id = node.get("id")
box = list(simpletransform.computeBBox([node]))
offset_x = box[0] - x
offset_y = box[2] - (y)
for cmd in path:
params = cmd[1]
i = 0
while i < len(params):
if i % 2 == 0:
# inkex.debug('x point at ' + str( round( params[i] )))
params[i] = params[i] - offset_x
# inkex.debug('moved to ' + str( round( params[i] )))
else:
# inkex.debug('y point at ' + str( round( params[i]) ))
params[i] = params[i] - offset_y
# inkex.debug('moved to ' + str( round( params[i] )))
i = i + 1
return simplepath.formatPath(path)
示例3: effect
def effect(self):
for id, node in self.selected.iteritems():
if node.tag == inkex.addNS('path','svg'):
p = simplepath.parsePath(node.get('d'))
a =[]
pen = None
subPathStart = None
for cmd,params in p:
if cmd == 'C':
a.extend([['M', params[:2]], ['L', pen],
['M', params[2:4]], ['L', params[-2:]]])
if cmd == 'Q':
a.extend([['M', params[:2]], ['L', pen],
['M', params[:2]], ['L', params[-2:]]])
if cmd == 'M':
subPathStart = params
if cmd == 'Z':
pen = subPathStart
else:
pen = params[-2:]
if len(a) > 0:
s = {'stroke-linejoin': 'miter', 'stroke-width': '1.0px',
'stroke-opacity': '1.0', 'fill-opacity': '1.0',
'stroke': '#000000', 'stroke-linecap': 'butt',
'fill': 'none'}
attribs = {'style':simplestyle.formatStyle(s),'d':simplepath.formatPath(a)}
inkex.etree.SubElement(node.getparent(), inkex.addNS('path','svg'), attribs)
示例4: load
def load(self, node, mat):
#JiB
#split the syle in separate tuples and assign to path
s = node.get('style')
if s:
self.style = s
for item in s.split(';'):
attribute , value = item.split(':')
#print attribute, value
value = value.replace('px', '')
setattr(self, attribute.replace('-','') , value)
#print getattr(self, attribute.replace('-','') )
#print ";" + self.strokewidth
#print attribute.replace('-','')
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.segments = []
for sp in p:
points = []
subdivideCubicPath(sp,0.2) # TODO: smoothness preference
for csp in sp:
points.append((csp[1][0],csp[1][1]))
self.segments.append(points)
示例5: convert_element_to_path
def convert_element_to_path(node):
"""Convert an SVG element into a simplepath.
This handles paths, rectangles, circles, ellipses, lines, and polylines.
Anything else raises and exception.
"""
node_tag = get_node_tag(node) # node tag stripped of namespace part
if node_tag == 'path':
return simplepath.parsePath(node.get('d'))
elif node_tag == 'rect':
return convert_rect_to_path(node)
elif node_tag == 'line':
return convert_line_to_path(node)
elif node_tag == 'circle':
return convert_circle_to_path(node)
elif node_tag == 'ellipse':
return convert_ellipse_to_path(node)
elif node_tag == 'polyline':
return convert_polyline_to_path(node)
elif node_tag == 'polygon':
return convert_polygon_to_path(node)
elif node_tag == 'text':
raise Exception(_('Unable to convert text; please convert text to paths first.'))
elif node_tag == 'image':
raise Exception(_('Unable to convert bitmap images; please convert them to line art first.'))
else:
raise Exception(_('Unable to convert this SVG element to a path: <%s>') % (node.tag))
示例6: 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) )
示例7: addDot
def addDot(self, node):
self.group = inkex.etree.SubElement(node.getparent(), inkex.addNS("g", "svg"))
self.dotGroup = inkex.etree.SubElement(self.group, inkex.addNS("g", "svg"))
self.numGroup = inkex.etree.SubElement(self.group, inkex.addNS("g", "svg"))
try:
t = node.get("transform")
self.group.set("transform", t)
except:
pass
style = simplestyle.formatStyle({"stroke": "none", "fill": "#000"})
a = []
p = simplepath.parsePath(node.get("d"))
self.separateLastAndFirst(p)
num = self.options.start
for cmd, params in p:
if cmd != "Z" and cmd != "z":
dot_att = {
"style": style,
"r": str(inkex.unittouu(self.options.dotsize) / 2),
"cx": str(params[-2]),
"cy": str(params[-1]),
}
inkex.etree.SubElement(self.dotGroup, inkex.addNS("circle", "svg"), dot_att)
self.addText(
self.numGroup,
params[-2] + (inkex.unittouu(self.options.dotsize) / 2),
params[-1] - (inkex.unittouu(self.options.dotsize) / 2),
num,
)
num += self.options.step
node.getparent().remove(node)
示例8: effect
def effect(self):
for id, node in self.selected.iteritems():
if node.tag == inkex.addNS('path', 'svg'):
d = node.get('d')
p = simplepath.parsePath(d)
last = []
subPathStart = []
for cmd,params in p:
if cmd == 'C':
if self.options.behave <= 1:
#shorten handles towards end points
params[:2] = pointAtPercent(params[:2],last[:],self.options.percent)
params[2:4] = pointAtPercent(params[2:4],params[-2:],self.options.percent)
else:
#shorten handles towards thirds of the segment
dest1 = pointAtPercent(last[:],params[-2:],33.3)
dest2 = pointAtPercent(params[-2:],last[:],33.3)
params[:2] = pointAtPercent(params[:2],dest1[:],self.options.percent)
params[2:4] = pointAtPercent(params[2:4],dest2[:],self.options.percent)
elif cmd == 'Q':
dest = pointAtPercent(last[:],params[-2:],50)
params[:2] = pointAtPercent(params[:2],dest,self.options.percent)
if cmd == 'M':
subPathStart = params[-2:]
if cmd == 'Z':
last = subPathStart[:]
else:
last = params[-2:]
node.set('d',simplepath.formatPath(p))
示例9: effect
def effect(self):
for id, node in self.selected.iteritems():
if node.tag == inkex.addNS('path','svg'):
self.group = inkex.etree.SubElement(node.getparent(),inkex.addNS('g','svg'))
new = inkex.etree.SubElement(self.group,inkex.addNS('path','svg'))
try:
t = node.get('transform')
self.group.set('transform', t)
except:
pass
s = simplestyle.parseStyle(node.get('style'))
s['stroke-linecap']='round'
s['stroke-width']=self.options.dotsize
new.set('style', simplestyle.formatStyle(s))
a =[]
p = simplepath.parsePath(node.get('d'))
num = 1
for cmd,params in p:
if cmd != 'Z':
a.append(['M',params[-2:]])
a.append(['L',params[-2:]])
self.addText(self.group,params[-2],params[-1],num)
num += 1
new.set('d', simplepath.formatPath(a))
node.clear()
示例10: path_bounding_box
def path_bounding_box(self, elem, parent_transform=None):
""" Returns [min_x, min_y], [max_x, max_y] of the transformed
element. (It doesn't make any sense to return the untransformed
bounding box, with the intent of transforming it later, because
the min/max points will be completely different points)
The returned bounding box includes stroke-width offset.
This function uses a simplistic algorithm & doesn't take curves
or arcs into account, just node positions.
"""
# If we have a Live Path Effect, modify original-d. If anyone clamours
# for it, we could make an option to ignore paths with Live Path Effects
original_d = "{%s}original-d" % inkex.NSS["inkscape"]
path = simplepath.parsePath(elem.attrib.get(original_d, elem.attrib["d"]))
transform = self.transform(elem, parent_transform=parent_transform)
offset = self.elem_offset(elem, parent_transform)
min_x = min_y = max_x = max_y = 0
for i in range(len(path)):
x, y = self.pathxy(path, i)
x, y = transform_point(transform, (x, y))
if i == 0:
min_x = max_x = x
min_y = max_y = y
else:
min_x = min(x, min_x)
min_y = min(y, min_y)
max_x = max(x, max_x)
max_y = max(y, max_y)
return (min_x - offset, min_y - offset), (max_x + offset, max_y + offset)
示例11: parseArc
def parseArc(self,node,parent):
#self.parsing_context = 'arc'
style = node.get('style')
style = self.parseStyleAttribute(style)
arc = {
'id':node.get('id',''),
'svg':'arc',
'label':str(node.get(inkex.addNS('label', 'inkscape'),'')),
'cx': node.get(inkex.addNS('cx', 'sodipodi'),''),
'cy':node.get(inkex.addNS('cy', 'sodipodi'),''),
'rx':node.get(inkex.addNS('rx', 'sodipodi'),''),
'ry':node.get(inkex.addNS('ry', 'sodipodi'),''),
'path':simplepath.parsePath(node.get('d')),
'd':node.get('d',''),
'box':list(simpletransform.computeBBox([node])),
'fill':style.get('fill',''),
'fill-opacity':style.get('fillOpacity',''),
'stroke':style.get('stroke',''),
'stroke-width':style.get('strokeWidth',''),
'stroke-opacity':style.get('strokeOpacity',''),
'transform':node.get('transform','')
}
if(self.reposition):
arc['path'] = self.movePath(node,0,0,'tl')
else:
arc['path'] = arc['d']
parent.append(arc)
示例12: convertToSegments
def convertToSegments(cls, path_node):
path_start = None
currentPoint = None
# work on copy to be shure not breaking anything
path = copy.deepcopy(path_node)
# apply transformation info on path, otherwise dealing with transform would be a mess
simpletransform.fuseTransform(path)
for cmd, params in simplepath.parsePath(path.get('d')):
print_('cmd, params', cmd, params)
if cmd == 'M':
if(path_start is None):
path_start = params
currentPoint = params
elif cmd == 'L':
yield Segment(currentPoint, params)
currentPoint = params
elif cmd in ['A', 'Q', 'C']:
yield Segment(currentPoint, params[-2:], command=cmd, extra_parameters=params[:-2])
currentPoint = params[-2:]
elif (cmd == 'Z'):
# Z is a line between the last point and the start of the shape
yield Segment(currentPoint, path_start)
currentPoint = None
path_start = None
else:
inkex.errormsg("Path Command %s not managed Yet" % cmd)
示例13: effect
def effect(self):
for id, node in self.selected.iteritems():
if node.tagName == 'path':
p = simplepath.parsePath(node.attributes.getNamedItem('d').value)
a =[]
pen = None
subPathStart = None
for cmd,params in p:
if cmd == 'C':
a.extend([['M', params[:2]], ['L', pen],
['M', params[2:4]], ['L', params[-2:]]])
if cmd == 'Q':
a.extend([['M', params[:2]], ['L', pen],
['M', params[:2]], ['L', params[-2:]]])
if cmd == 'M':
subPathStart = params
if cmd == 'Z':
pen = subPathStart
else:
pen = params[-2:]
if len(a) > 0:
new = self.document.createElement('svg:path')
s = {'stroke-linejoin': 'miter', 'stroke-width': '1.0px',
'stroke-opacity': '1.0', 'fill-opacity': '1.0',
'stroke': '#000000', 'stroke-linecap': 'butt',
'fill': 'none'}
new.setAttribute('style', simplestyle.formatStyle(s))
new.setAttribute('d', simplepath.formatPath(a))
node.parentNode.appendChild(new)
示例14: snap_path_scale
def snap_path_scale(self, elem, parent_transform=None):
# If we have a Live Path Effect, modify original-d. If anyone clamours
# for it, we could make an option to ignore paths with Live Path Effects
original_d = "{%s}original-d" % inkex.NSS["inkscape"]
path = simplepath.parsePath(elem.attrib.get(original_d, elem.attrib["d"]))
transform = self.transform(elem, parent_transform=parent_transform)
min_xy, max_xy = self.path_bounding_box(elem, parent_transform)
width = max_xy[0] - min_xy[0]
height = max_xy[1] - min_xy[1]
# In case somebody tries to snap a 0-high element,
# or a curve/arc with all nodes in a line, and of course
# because we should always check for divide-by-zero!
if width == 0 or height == 0:
return
rescale = round(width) / width, round(height) / height
min_xy = transform_point(transform, min_xy, inverse=True)
max_xy = transform_point(transform, max_xy, inverse=True)
for i in range(len(path)):
self.transform_path_node([[1, 0, -min_xy[0]], [0, 1, -min_xy[1]]], path, i) # center transform
self.transform_path_node([[rescale[0], 0, 0], [0, rescale[1], 0]], path, i)
self.transform_path_node([[1, 0, +min_xy[0]], [0, 1, +min_xy[1]]], path, i) # uncenter transform
path = simplepath.formatPath(path)
if original_d in elem.attrib:
elem.attrib[original_d] = path
else:
elem.attrib["d"] = path
示例15: snap_path_scale
def snap_path_scale(self, elem, parent_transform=None):
# If we have a Live Path Effect, modify original-d. If anyone clamours
# for it, we could make an option to ignore paths with Live Path Effects
original_d = '{%s}original-d' % inkex.NSS['inkscape']
path = simplepath.parsePath(elem.attrib.get(original_d, elem.attrib['d']))
transform = self.transform(elem, parent_transform=parent_transform)
min_xy, max_xy = self.path_bounding_box(elem, parent_transform)
width = max_xy[0] - min_xy[0]
height = max_xy[1] - min_xy[1]
rescale = round(width)/width, round(height)/height
min_xy = transform_point(transform, min_xy, inverse=True)
max_xy = transform_point(transform, max_xy, inverse=True)
for i in range(len(path)):
self.transform_path_node([[1, 0, -min_xy[0]], [0, 1, -min_xy[1]]], path, i) # center transform
self.transform_path_node([[rescale[0], 0, 0],
[0, rescale[1], 0]],
path, i)
self.transform_path_node([[1, 0, +min_xy[0]], [0, 1, +min_xy[1]]], path, i) # uncenter transform
path = simplepath.formatPath(path)
if original_d in elem.attrib: elem.attrib[original_d] = path
else: elem.attrib['d'] = path