def multiplyLine(line, num):
"""
Takes a list of coordinates and returns a list
(containing 'num' items) of lists of coordinates.
"""
import math
width = 80
def vec_normalize(vec):
x, y = vec
veclen = math.sqrt(x * x + y * y)
return (0, 0) if veclen == 0 else (x / veclen, y / veclen)
if num <= 1:
return line
if len(line) < 2:
return [line for _ in range(num)]
new_lines = [[] for _ in range(num)]
numinv = 1 / float(num - 1)
for (j, (old_x, old_y)) in enumerate(line):
first = j == 0
last = j == len(line) - 1
if not last:
old_x2, old_y2 = line[j + 1]
(vec_x1, vec_y1) = vec_normalize((old_y2 - old_y, -old_x2 + old_x))
if not first:
old_x3, old_y3 = line[j - 1]
(vec_x2, vec_y2) = vec_normalize((-old_y3 + old_y, old_x3 - old_x))
if not first and not last:
(vec_x3, vec_y3) = vec_normalize((vec_x1 + vec_x2, vec_y1 + vec_y2))
len_corr = math.sin((math.pi - math.acos(vec_x1 * vec_x2 + vec_y1 * vec_y2)) / 2)
len_corr = 1 if len_corr == 0 else len_corr
(vec_x3, vec_y3) = (vec_x3 / len_corr, vec_y3 / len_corr)
for (i, new_line) in enumerate(new_lines):
factor = width * (i * numinv - 0.5)
(vec_x, vec_y) = (vec_x1, vec_y1) if first else (vec_x2, vec_y2) if last else (vec_x3, vec_y3)
new_line.append((vec_x * factor + old_x, vec_y * factor + old_y))
return new_lines
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class Foo(QWidget):
def paintEvent(self, event):
painter = QPainter(self)
painter.save()
line = [(100, 100), (300, 200), (500, 200), (300, 500), (600, 450), (650, 180), (800, 180), (800, 500), (200, 700)]
lines = multiplyLine(line, 14)
path = QPainterPath()
for (i, (x, y)) in enumerate(line):
if i == 0:
path.moveTo(x, y)
else:
path.lineTo(x, y)
painter.setPen(QPen(QColor(255, 0, 0), 1, Qt.SolidLine, Qt.FlatCap, Qt.MiterJoin))
painter.drawPath(path)
path = QPainterPath()
for line in lines:
for (i, (x, y)) in enumerate(line):
if i == 0:
path.moveTo(x, y)
else:
path.lineTo(x, y)
painter.setPen(QPen(QColor(0, 0, 0), 1, Qt.SolidLine, Qt.FlatCap, Qt.MiterJoin))
painter.drawPath(path)
painter.restore()
app = QApplication(sys.argv)
foo = Foo()
foo.show()
foo.resize(1000, 800)
sys.exit(app.exec_())