/
toolbox.py
95 lines (68 loc) · 2.71 KB
/
toolbox.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
__author__ = 'smuthunoori'
import kivy
kivy.require('1.7.0')
import math
from kivy.uix.togglebutton import ToggleButton
from kivy.graphics import Line
from comicwidgets import StickMan, DraggableWidget
class ToolButton(ToggleButton):
def on_touch_down(self, touch):
ds = self.parent.drawing_space
#print 'ToolButton: touch_down'
if self.state == 'down' and ds.collide_point(touch.x, touch.y):
#print 'ToolButton: touch_down collided'
(x,y) = ds.to_widget(touch.x, touch.y)
self.draw(ds, x, y)
return True
return super(ToolButton, self).on_touch_down(touch)
def draw(self, ds, x, y):
pass
class ToolStickMan(ToolButton):
def draw(self, ds, x, y):
sm = StickMan(width=48, height=48)
sm.center = (x,y)
ds.add_widget(sm)
class ToolFigure(ToolButton):
def draw(self, ds, x, y):
(self.ix, self.iy) = (x, y)
with ds.canvas:
self.figure = self.create_figure(x, y, x+1, y+1)
ds.bind(on_touch_move=self.update_figure)
ds.bind(on_touch_up=self.end_figure)
def update_figure(self, ds, touch):
if ds.collide_point(touch.x, touch.y):
(x,y) = ds.to_widget(touch.x, touch.y)
ds.canvas.remove(self.figure)
with ds.canvas:
self.figure = self.create_figure(self.ix, self.iy, x, y)
def end_figure(self, ds, touch):
ds.unbind(on_touch_move=self.update_figure)
ds.unbind(on_touch_up=self.end_figure)
ds.canvas.remove(self.figure)
(fx,fy) = ds.to_widget(touch.x, touch.y)
self.widgetize(ds, self.ix, self.iy, fx, fy)
def widgetize(self, ds, ix, iy, fx, fy):
widget = self.create_widget(ix, iy, fx, fy)
(ix,iy) = widget.to_local(ix, iy, relative=True)
(fx,fy) = widget.to_local(fx, fy, relative=True)
widget.canvas.add(self.create_figure(ix, iy, fx, fy))
ds.add_widget(widget)
def create_figure(self, ix, iy, fx, fy):
pass
def create_widget(self, ix, iy, fx, fy):
pass
class ToolCircle(ToolFigure):
def create_figure(self, ix, iy, fx, fy):
return Line(circle=[ix, iy, math.hypot(ix-fx, iy-fy)])
def create_widget(self, ix, iy, fx, fy):
radius = math.hypot(ix-fx, iy-fy)
pos = (ix-radius, iy-radius)
size = (2*radius, 2*radius)
return DraggableWidget(pos=pos, size=size)
class ToolLine(ToolFigure):
def create_figure(self, ix, iy, fx, fy):
return Line(points=[ix, iy, fx, fy])
def create_widget(self, ix, iy, fx, fy):
pos = (min(ix, fx), min(iy, fy))
size = (abs(fx-ix), abs(fy-iy))
return DraggableWidget(pos=pos, size=size)