Created
August 11, 2011 20:14
-
-
Save jl2/1140629 to your computer and use it in GitHub Desktop.
Draw Bezier curves using Python and PyQt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
import random | |
import functools | |
from PyQt4 import QtGui, QtCore | |
@functools.lru_cache(maxsize=100) | |
def factorial(n): | |
prod = 1 | |
for i in range(1,n+1): | |
prod *= i | |
return prod | |
def randPt(minv, maxv): | |
return (random.randint(minv, maxv), random.randint(minv, maxv)) | |
def B(i,n,u): | |
val = factorial(n)/(factorial(i)*factorial(n-i)) | |
return val * (u**i) * ((1-u)**(n-i)) | |
def C(u, pts): | |
x = 0 | |
y = 0 | |
n = len(pts)-1 | |
for i in range(n+1): | |
binu = B(i,n,u) | |
x += binu * pts[i][0] | |
y += binu * pts[i][1] | |
return (x, y) | |
class BezierDrawer(QtGui.QWidget): | |
def __init__(self): | |
super(BezierDrawer, self).__init__() | |
self.setGeometry(300, 300, 1000,1000) | |
self.setWindowTitle('Bezier Curves') | |
def paintEvent(self, e): | |
qp = QtGui.QPainter() | |
qp.begin(self) | |
qp.setRenderHints(QtGui.QPainter.Antialiasing, True) | |
self.doDrawing(qp) | |
qp.end() | |
def doDrawing(self, qp): | |
blackPen = QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.DashLine) | |
redPen = QtGui.QPen(QtCore.Qt.red, 1, QtCore.Qt.DashLine) | |
bluePen = QtGui.QPen(QtCore.Qt.blue, 1, QtCore.Qt.DashLine) | |
greenPen = QtGui.QPen(QtCore.Qt.green, 1, QtCore.Qt.DashLine) | |
redBrush = QtGui.QBrush(QtCore.Qt.red) | |
steps = 400 | |
min_t = 0.0 | |
max_t = 1.0 | |
dt = (max_t - min_t)/steps | |
# controlPts = [randPt(0,1000) for i in range(6)] | |
# controlPts.append(controlPts[1]) | |
# controlPts.append(controlPts[0]) | |
controlPts = [(100,100), (600,100), (600,600), (100,600)] | |
oldPt = controlPts[0] | |
pn = 1 | |
qp.setPen(redPen) | |
qp.setBrush(redBrush) | |
qp.drawEllipse(oldPt[0]-3, oldPt[1]-3, 6,6) | |
qp.drawText(oldPt[0]+5, oldPt[1]-3, '{}'.format(pn)) | |
for pt in controlPts[1:]: | |
pn+=1 | |
qp.setPen(blackPen) | |
qp.drawLine(oldPt[0],oldPt[1],pt[0],pt[1]) | |
qp.setPen(redPen) | |
qp.drawEllipse(pt[0]-3, pt[1]-3, 6,6) | |
qp.drawText(pt[0]+5, pt[1]-3, '{}'.format(pn)) | |
oldPt = pt | |
qp.setPen(bluePen) | |
oldPt = controlPts[0] | |
for i in range(steps+1): | |
t = dt*i | |
pt = C(t, controlPts) | |
qp.drawLine(oldPt[0],oldPt[1], pt[0],pt[1]) | |
oldPt = pt | |
def main(args): | |
app = QtGui.QApplication(sys.argv) | |
ex = BezierDrawer() | |
ex.show() | |
app.exec_() | |
if __name__=='__main__': | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment