在Python中查找SVG路径元素的最终位置

2024-09-30 01:30:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在处理svgwrite模块,我想使用路径元素的字符串计算路径元素的结束位置。 例如:

"m151,200 105,60 M250,200 A100,100 0 1,1 200,0 c0,0 0,0 -16,120 c0,0 0,0 -84,46 c-4,-5 0,0 -84,-46 c-20,0 0,0 -16,-120 z"

我创建了一个函数来实现这一点,它可以工作,但有点笨重

def pathPos(path, debug=0): #Gets ending position of path
    posCrawl = {'m':lambda a: [list(map(int, i.split(','))) for i in a[1:].split()[0::1]], #Find pos argment based on instruction
                'l':lambda a: [list(map(int, i.split(','))) for i in a[1:].split()[0::1]],
                'h':lambda a: [(int(i), 0) for i in a[1:].split()[0::1]],
                'v':lambda a: [(0, int(i)) for i in a[1:].split()[0::1]],
                'c':lambda a: [list(map(int, i.split(','))) for i in a[1:].split()[2::3]],
                's':lambda a: [list(map(int, i.split(','))) for i in a[1:].split()[1::2]],
                'q':lambda a: [list(map(int, i.split(','))) for i in a[1:].split()[1::2]],
                't':lambda a: [list(map(int, i.split(','))) for i in a[1:].split()[0::1]],
                'a':lambda a: [list(map(int, i.split(','))) for i in a[1:].split()[3::4]]}
    args = re.findall("([MmLlZzHhVvCcSsQqTtAa][^MmLlZzHhVvCcSsQqTtAa]*)", path) #Create list of all path instructions with their arguments
    initialPos = [0,0]
    currentPos = [0,0]
    for arg in args:
        if debug:
            print(arg)
        if arg[0].isupper(): #Check if instruction is absolute...
            if arg[0].lower() == 'm': #M/m is a special case because it sets the initial position that Z/z returns to
                initialPos = posCrawl['m'](arg)[0] #absolute sets value
                currentPos = posCrawl['m'](arg)[-1]
            elif arg[0].lower() == 'z':
                currentPos = initialPos #Special case that closes path (returns to initial position)
            else:
                currentPos = posCrawl[arg[0].lower()](arg)[-1]
        elif arg[0].islower():#...or relative
            if arg[0].lower() == 'm':
                initialPos = [sum(x) for x in zip(initialPos, posCrawl['m'](arg)[0])] #relative adds value
                currentPos = [sum(x) for x in zip(*(posCrawl['m'](arg)+[currentPos]))]
            elif arg[0].lower() == 'z':
                currentPos = initialPos
            else:
                currentPos = [sum(x) for x in zip(*(posCrawl[arg[0]](arg)+[currentPos]))]
        if debug:
            print(currentPos)
            print()
    print(currentPos)

我怎样才能改进它


Tags: pathlambdainmapforifarglower

热门问题