drawSvg 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of drawSvg might be problematic. Click here for more details.
- drawSvg-1.0.0/PKG-INFO +12 -0
- drawSvg-1.0.0/drawSvg/__init__.py +62 -0
- drawSvg-1.0.0/drawSvg/color.py +199 -0
- drawSvg-1.0.0/drawSvg/defs.py +67 -0
- drawSvg-1.0.0/drawSvg/drawing.py +146 -0
- drawSvg-1.0.0/drawSvg/elements.py +353 -0
- drawSvg-1.0.0/drawSvg/missing.py +7 -0
- drawSvg-1.0.0/drawSvg/raster.py +43 -0
- drawSvg-1.0.0/setup.cfg +3 -0
- drawSvg-1.0.0/setup.py +15 -0
drawSvg-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 1.1
|
|
2
|
+
Name: drawSvg
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: This is a Python 3 library for programmatically generating SVG images (vector drawings) and rendering them or displaying them in an iPython notebook.
|
|
5
|
+
Home-page: https://github.com/cduck/drawSvg
|
|
6
|
+
Author: Casey Duckering
|
|
7
|
+
Author-email: UNKNOWN
|
|
8
|
+
License: UNKNOWN
|
|
9
|
+
Download-URL: https://github.com/cduck/drawSvg/archive/1.0.0.tar.gz
|
|
10
|
+
Description: UNKNOWN
|
|
11
|
+
Keywords: SVG,draw,graphics,iPython,Jupyter
|
|
12
|
+
Platform: UNKNOWN
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
'''
|
|
2
|
+
A library for creating SVG files or just drawings that can be displayed in
|
|
3
|
+
iPython notebooks
|
|
4
|
+
|
|
5
|
+
Example:
|
|
6
|
+
```
|
|
7
|
+
d = draw.Drawing(200, 100, origin='center')
|
|
8
|
+
|
|
9
|
+
d.append(draw.Lines(-80, -45,
|
|
10
|
+
70, -49,
|
|
11
|
+
95, 49,
|
|
12
|
+
-90, 40,
|
|
13
|
+
close=False,
|
|
14
|
+
fill='#eeee00',
|
|
15
|
+
stroke='black'))
|
|
16
|
+
|
|
17
|
+
d.append(draw.Rectangle(0,0,40,50, fill='#1248ff'))
|
|
18
|
+
d.append(draw.Circle(-40, -10, 30,
|
|
19
|
+
fill='red', stroke_width=2, stroke='black'))
|
|
20
|
+
|
|
21
|
+
p = draw.Path(stroke_width=2, stroke='green',
|
|
22
|
+
fill='black', fill_opacity=0.5)
|
|
23
|
+
p.M(-30,5) # Start path at point (-30, 5)
|
|
24
|
+
p.l(60,30) # Draw line to (60, 30)
|
|
25
|
+
p.h(-70) # Draw horizontal line to x=-70
|
|
26
|
+
p.Z() # Draw line to start
|
|
27
|
+
d.append(p)
|
|
28
|
+
|
|
29
|
+
d.append(draw.ArcLine(60,-20,20,60,270,
|
|
30
|
+
stroke='red', stroke_width=5, fill='red', fill_opacity=0.2))
|
|
31
|
+
d.append(draw.Arc(60,-20,20,60,270,cw=False,
|
|
32
|
+
stroke='green', stroke_width=3, fill='none'))
|
|
33
|
+
d.append(draw.Arc(60,-20,20,270,60,cw=True,
|
|
34
|
+
stroke='blue', stroke_width=1, fill='black', fill_opacity=0.3))
|
|
35
|
+
|
|
36
|
+
d.setPixelScale(2) # Set number of pixels per geometry unit
|
|
37
|
+
#d.setRenderSize(400,200) # Alternative to setPixelScale
|
|
38
|
+
d.saveSvg('example.svg')
|
|
39
|
+
d.savePng('example.png')
|
|
40
|
+
|
|
41
|
+
# Display in iPython notebook
|
|
42
|
+
d.rasterize() # Display as PNG
|
|
43
|
+
d # Display as SVG
|
|
44
|
+
```
|
|
45
|
+
'''
|
|
46
|
+
|
|
47
|
+
from .defs import *
|
|
48
|
+
from .raster import Raster
|
|
49
|
+
from .drawing import Drawing
|
|
50
|
+
from .elements import *
|
|
51
|
+
|
|
52
|
+
# Make all elements available in the elements module
|
|
53
|
+
from . import defs
|
|
54
|
+
from . import elements
|
|
55
|
+
def registerElement(name, elem):
|
|
56
|
+
setattr(elements, name, elem)
|
|
57
|
+
elementsDir = dir(elements)
|
|
58
|
+
for k in dir(defs):
|
|
59
|
+
if k.startswith('_'): continue
|
|
60
|
+
if k in elementsDir: continue
|
|
61
|
+
registerElement(k, getattr(defs, k))
|
|
62
|
+
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
|
|
2
|
+
import math
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pwkit.colormaps # pip3 install pwkit
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
# Most calculations from http://www.chilliant.com/rgb2hsv.html
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def limit(v, low=0, high=1):
|
|
11
|
+
return max(min(v, high), low)
|
|
12
|
+
|
|
13
|
+
class Srgb:
|
|
14
|
+
LUMA_WEIGHTS = (0.299, 0.587, 0.114)
|
|
15
|
+
def __init__(self, r, g, b):
|
|
16
|
+
self.r = float(r)
|
|
17
|
+
self.g = float(g)
|
|
18
|
+
self.b = float(b)
|
|
19
|
+
def __iter__(self):
|
|
20
|
+
return iter((self.r, self.g, self.b))
|
|
21
|
+
def __repr__(self):
|
|
22
|
+
return 'RGB({}, {}, {})'.format(self.r, self.g, self.b)
|
|
23
|
+
def __str__(self):
|
|
24
|
+
return 'rgb({}%,{}%,{}%)'.format(self.r*100, self.g*100, self.b*100)
|
|
25
|
+
def luma(self, wts=None):
|
|
26
|
+
if wts is None: wts = self.LUMA_WEIGHTS
|
|
27
|
+
rw, gw, bw = wts
|
|
28
|
+
return rw*self.r + gw*self.g + bw*self.b
|
|
29
|
+
def toSrgb(self):
|
|
30
|
+
return self
|
|
31
|
+
@staticmethod
|
|
32
|
+
def fromHue(h):
|
|
33
|
+
h = h % 1
|
|
34
|
+
r = abs(h * 6 - 3) - 1
|
|
35
|
+
g = 2 - abs(h * 6 - 2)
|
|
36
|
+
b = 2 - abs(h * 6 - 4)
|
|
37
|
+
return Srgb(limit(r), limit(g), limit(b))
|
|
38
|
+
|
|
39
|
+
class Hsl:
|
|
40
|
+
def __init__(self, h, s, l):
|
|
41
|
+
self.h = float(h) % 1
|
|
42
|
+
self.s = float(s)
|
|
43
|
+
self.l = float(l)
|
|
44
|
+
def __iter__(self):
|
|
45
|
+
return iter((self.h, self.s, self.l))
|
|
46
|
+
def __repr__(self):
|
|
47
|
+
return 'HSL({}, {}, {})'.format(self.h, self.s, self.l)
|
|
48
|
+
def __str__(self):
|
|
49
|
+
r, g, b = self.toSrgb()
|
|
50
|
+
return 'rgb({}%,{}%,{}%)'.format(round(r*100), round(g*100), round(b*100))
|
|
51
|
+
def toSrgb(self):
|
|
52
|
+
hs = Srgb.fromHue(self.h)
|
|
53
|
+
c = (1 - abs(2 * self.l - 1)) * self.s
|
|
54
|
+
return Srgb(
|
|
55
|
+
(hs.r - 0.5) * c + self.l,
|
|
56
|
+
(hs.g - 0.5) * c + self.l,
|
|
57
|
+
(hs.b - 0.5) * c + self.l
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
class Hsv:
|
|
61
|
+
def __init__(self, h, s, v):
|
|
62
|
+
self.h = float(h) % 1
|
|
63
|
+
self.s = float(s)
|
|
64
|
+
self.v = float(v)
|
|
65
|
+
def __iter__(self):
|
|
66
|
+
return iter((self.h, self.s, self.v))
|
|
67
|
+
def __repr__(self):
|
|
68
|
+
return 'HSV({}, {}, {})'.format(self.h, self.s, self.v)
|
|
69
|
+
def __str__(self):
|
|
70
|
+
r, g, b = self.toSrgb()
|
|
71
|
+
return 'rgb({}%,{}%,{}%)'.format(round(r*100), round(g*100), round(b*100))
|
|
72
|
+
def toSrgb(self):
|
|
73
|
+
hs = Srgb.fromHue(self.h)
|
|
74
|
+
c = self.v * self.s
|
|
75
|
+
hp = self.h * 6
|
|
76
|
+
x = c * (1 - abs(hp % 2 - 1))
|
|
77
|
+
if hp < 1:
|
|
78
|
+
r1, g1, b1 = c, x, 0
|
|
79
|
+
elif hp < 2:
|
|
80
|
+
r1, g1, b1 = x, c, 0
|
|
81
|
+
elif hp < 3:
|
|
82
|
+
r1, g1, b1 = 0, c, x
|
|
83
|
+
elif hp < 4:
|
|
84
|
+
r1, g1, b1 = 0, x, c
|
|
85
|
+
elif hp < 5:
|
|
86
|
+
r1, g1, b1 = x, 0, c
|
|
87
|
+
else:
|
|
88
|
+
r1, g1, b1 = c, 0, x
|
|
89
|
+
m = self.v - c
|
|
90
|
+
return Srgb(r1+m, g1+m, b1+m)
|
|
91
|
+
|
|
92
|
+
class Sin:
|
|
93
|
+
def __init__(self, h, s, l):
|
|
94
|
+
self.h = float(h) % 1
|
|
95
|
+
self.s = float(s)
|
|
96
|
+
self.l = float(l)
|
|
97
|
+
def __iter__(self):
|
|
98
|
+
return iter((self.h, self.s, self.l))
|
|
99
|
+
def __repr__(self):
|
|
100
|
+
return 'Sin({}, {}, {})'.format(self.h, self.s, self.l)
|
|
101
|
+
def __str__(self):
|
|
102
|
+
r, g, b = self.toSrgb()
|
|
103
|
+
return 'rgb({}%,{}%,{}%)'.format(round(r*100), round(g*100), round(b*100))
|
|
104
|
+
def toSrgb(self):
|
|
105
|
+
h = self.h
|
|
106
|
+
scale = self.s / 2
|
|
107
|
+
shift = self.l #* (1-2*scale)
|
|
108
|
+
return Srgb(
|
|
109
|
+
shift + scale * math.cos(math.pi*2 * (h - 0/6)),
|
|
110
|
+
shift + scale * math.cos(math.pi*2 * (h - 2/6)),
|
|
111
|
+
shift + scale * math.cos(math.pi*2 * (h - 4/6)),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
class Hcy:
|
|
115
|
+
HCY_WEIGHTS = Srgb.LUMA_WEIGHTS
|
|
116
|
+
def __init__(self, h, c, y):
|
|
117
|
+
self.h = float(h) % 1
|
|
118
|
+
self.c = float(c)
|
|
119
|
+
self.y = float(y)
|
|
120
|
+
def __iter__(self):
|
|
121
|
+
return iter((self.h, self.c, self.y))
|
|
122
|
+
def __repr__(self):
|
|
123
|
+
return 'HCY({}, {}, {})'.format(self.h, self.c, self.y)
|
|
124
|
+
def __str__(self):
|
|
125
|
+
r, g, b = self.toSrgb()
|
|
126
|
+
return 'rgb({}%,{}%,{}%)'.format(r*100, g*100, b*100)
|
|
127
|
+
def toSrgb(self):
|
|
128
|
+
hs = Srgb.fromHue(self.h)
|
|
129
|
+
y = hs.luma(wts=self.HCY_WEIGHTS)
|
|
130
|
+
c = self.c
|
|
131
|
+
if self.y < y:
|
|
132
|
+
c *= self.y / y
|
|
133
|
+
elif y < 1:
|
|
134
|
+
c *= (1 - self.y) / (1 - y)
|
|
135
|
+
return Srgb(
|
|
136
|
+
(hs.r - y) * c + self.y,
|
|
137
|
+
(hs.g - y) * c + self.y,
|
|
138
|
+
(hs.b - y) * c + self.y,
|
|
139
|
+
)
|
|
140
|
+
@staticmethod
|
|
141
|
+
def _rgbToHcv(srgb):
|
|
142
|
+
if srgb.g < srgb.b:
|
|
143
|
+
p = (srgb.b, srgb.g, -1., 2./3.)
|
|
144
|
+
else:
|
|
145
|
+
p = (srgb.g, srgb.b, 0., -1./3.)
|
|
146
|
+
if srgb.r < p[0]:
|
|
147
|
+
q = (p[0], p[1], p[3], srgb.r)
|
|
148
|
+
else:
|
|
149
|
+
q = (srgb.r, p[1], p[2], p[0])
|
|
150
|
+
c = q[0] - min(q[3], q[1])
|
|
151
|
+
h = abs((q[3] - q[1]) / (6*c + 1e-10) + q[2])
|
|
152
|
+
return (h, c, q[0])
|
|
153
|
+
@classmethod
|
|
154
|
+
def fromSrgb(cls, srgb):
|
|
155
|
+
hcv = list(cls._rgbToHcv(srgb))
|
|
156
|
+
rw, gw, bw = cls.HCY_WEIGHTS
|
|
157
|
+
y = rw*srgb.r + gw*srgb.g + bw*srgb.b
|
|
158
|
+
hs = Srgb.fromHue(hcv[0])
|
|
159
|
+
z = rw*hs.r + gw*hs.g + bw*hs.b
|
|
160
|
+
if y < z:
|
|
161
|
+
hcv[1] *= z / (y + 1e-10)
|
|
162
|
+
else:
|
|
163
|
+
hcv[1] *= (1 - z) / (1 - y + 1e-10)
|
|
164
|
+
return Hcy(hcv[0], hcv[1], y)
|
|
165
|
+
|
|
166
|
+
class Cielab:
|
|
167
|
+
REF_WHITE = (0.95047, 1., 1.08883)
|
|
168
|
+
def __init__(self, l, a, b):
|
|
169
|
+
self.l = float(l)
|
|
170
|
+
self.a = float(a)
|
|
171
|
+
self.b = float(b)
|
|
172
|
+
def __iter__(self):
|
|
173
|
+
return iter((self.l, self.a, self.b))
|
|
174
|
+
def __repr__(self):
|
|
175
|
+
return 'CIELAB({}, {}, {})'.format(self.l, self.a, self.b)
|
|
176
|
+
def __str__(self):
|
|
177
|
+
r, g, b = self.toSrgb()
|
|
178
|
+
return 'rgb({}%,{}%,{}%)'.format(round(r*100), round(g*100), round(b*100))
|
|
179
|
+
def toSrgb(self):
|
|
180
|
+
inArr = np.array((*self.l,), dtype=float)
|
|
181
|
+
xyz = pwkit.colormaps.cielab_to_xyz(inArr, self.REF_WHITE)
|
|
182
|
+
linSrgb = pwkit.colormaps.xyz_to_linsrgb(xyz)
|
|
183
|
+
r, g, b = pwkit.colormaps.linsrgb_to_srgb(linSrgb)
|
|
184
|
+
return Srgb(r, g, b)
|
|
185
|
+
@classmethod
|
|
186
|
+
def fromSrgb(cls, srgb, refWhite=None):
|
|
187
|
+
if refWhite is None: refWhite = cls.REF_WHITE
|
|
188
|
+
inArr = np.array((*srgb,), dtype=float)
|
|
189
|
+
linSrgb = pwkit.colormaps.srgb_to_linsrgb(inArr)
|
|
190
|
+
xyz = pwkit.colormaps.linsrgb_to_xyz(linSrgb)
|
|
191
|
+
l, a, b = pwkit.colormaps.xyz_to_cielab(xyz, refWhite)
|
|
192
|
+
return Cielab(l, a, b)
|
|
193
|
+
def toSrgb(self):
|
|
194
|
+
inArr = np.array((self.l, self.a, self.b))
|
|
195
|
+
xyz = pwkit.colormaps.cielab_to_xyz(inArr, self.REF_WHITE)
|
|
196
|
+
linSrgb = pwkit.colormaps.xyz_to_linsrgb(xyz)
|
|
197
|
+
r, g, b = pwkit.colormaps.linsrgb_to_srgb(linSrgb)
|
|
198
|
+
return Srgb(r, g, b)
|
|
199
|
+
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
|
|
2
|
+
from .elements import DrawingElement, DrawingParentElement
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class DrawingDef(DrawingParentElement):
|
|
6
|
+
''' Parent class of SVG nodes that must be direct children of <defs> '''
|
|
7
|
+
def getSvgDefs(self):
|
|
8
|
+
return (self,)
|
|
9
|
+
def writeSvgDefs(self, idGen, isDuplicate, outputFile):
|
|
10
|
+
DrawingElement.writeSvgDefs(idGen, isDuplicate, outputFile)
|
|
11
|
+
|
|
12
|
+
class DrawingDefSub(DrawingParentElement):
|
|
13
|
+
''' Parent class of SVG nodes that are meant to be descendants of a Def '''
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
class LinearGradient(DrawingDef):
|
|
17
|
+
''' A linear gradient to use as a fill or other color
|
|
18
|
+
|
|
19
|
+
Has <stop> nodes as children. '''
|
|
20
|
+
TAG_NAME = 'linearGradient'
|
|
21
|
+
def __init__(self, x1, y1, x2, y2, gradientUnits='userSpaceOnUse', **kwargs):
|
|
22
|
+
yShift = 0
|
|
23
|
+
if gradientUnits != 'userSpaceOnUse':
|
|
24
|
+
yShift = 1
|
|
25
|
+
try: y1 = yShift - y1
|
|
26
|
+
except TypeError: pass
|
|
27
|
+
try: y2 = yShift - y2
|
|
28
|
+
except TypeError: pass
|
|
29
|
+
super().__init__(x1=x1, y1=y1, x2=x2, y2=y2, gradientUnits=gradientUnits,
|
|
30
|
+
**kwargs)
|
|
31
|
+
def addStop(self, offset, color, opacity=None, **kwargs):
|
|
32
|
+
stop = GradientStop(offset=offset, stop_color=color,
|
|
33
|
+
stop_opacity=opacity, **kwargs)
|
|
34
|
+
self.append(stop)
|
|
35
|
+
|
|
36
|
+
class RadialGradient(DrawingDef):
|
|
37
|
+
''' A radial gradient to use as a fill or other color
|
|
38
|
+
|
|
39
|
+
Has <stop> nodes as children. '''
|
|
40
|
+
TAG_NAME = 'radialGradient'
|
|
41
|
+
def __init__(self, cx, cy, r, gradientUnits='userSpaceOnUse', fy=None, **kwargs):
|
|
42
|
+
yShift = 0
|
|
43
|
+
if gradientUnits != 'userSpaceOnUse':
|
|
44
|
+
yShift = 1
|
|
45
|
+
try: cy = yShift - cy
|
|
46
|
+
except TypeError: pass
|
|
47
|
+
try: fy = yShift - fy
|
|
48
|
+
except TypeError: pass
|
|
49
|
+
super().__init__(cx=cx, cy=cy, r=r, gradientUnits=gradientUnits,
|
|
50
|
+
fy=fy, **kwargs)
|
|
51
|
+
def addStop(self, offset, color, opacity=None, **kwargs):
|
|
52
|
+
stop = GradientStop(offset=offset, stop_color=color,
|
|
53
|
+
stop_opacity=opacity, **kwargs)
|
|
54
|
+
self.append(stop)
|
|
55
|
+
|
|
56
|
+
class GradientStop(DrawingDefSub):
|
|
57
|
+
''' A control point for a radial or linear gradient '''
|
|
58
|
+
TAG_NAME = 'stop'
|
|
59
|
+
hasContent = False
|
|
60
|
+
|
|
61
|
+
class ClipPath(DrawingDef):
|
|
62
|
+
''' A shape used to crop another element by not drawing outside of this
|
|
63
|
+
shape
|
|
64
|
+
|
|
65
|
+
Has regular drawing elements as children. '''
|
|
66
|
+
TAG_NAME = 'clipPath'
|
|
67
|
+
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
|
|
2
|
+
from io import StringIO
|
|
3
|
+
|
|
4
|
+
from . import Raster
|
|
5
|
+
from . import elements as elementsModule
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Drawing:
|
|
9
|
+
''' A canvas to draw on
|
|
10
|
+
|
|
11
|
+
Supports iPython: If a Drawing is the last line of a cell, it will be
|
|
12
|
+
displayed as an SVG below. '''
|
|
13
|
+
def __init__(self, width, height, origin=(0,0), **svgArgs):
|
|
14
|
+
assert float(width) == width
|
|
15
|
+
assert float(height) == height
|
|
16
|
+
self.width = width
|
|
17
|
+
self.height = height
|
|
18
|
+
if origin == 'center':
|
|
19
|
+
self.viewBox = (width/2, height/2, width, height)
|
|
20
|
+
else:
|
|
21
|
+
origin = tuple(origin)
|
|
22
|
+
assert len(origin) == 2
|
|
23
|
+
self.viewBox = origin + (width, height)
|
|
24
|
+
self.viewBox = (-self.viewBox[0], self.viewBox[1]-self.viewBox[3],
|
|
25
|
+
self.viewBox[2], self.viewBox[3])
|
|
26
|
+
self.elements = []
|
|
27
|
+
self.otherDefs = []
|
|
28
|
+
self.pixelScale = 1
|
|
29
|
+
self.renderWidth = None
|
|
30
|
+
self.renderHeight = None
|
|
31
|
+
self.svgArgs = svgArgs
|
|
32
|
+
def setRenderSize(self, w=None, h=None):
|
|
33
|
+
self.renderWidth = w
|
|
34
|
+
self.renderHeight = h
|
|
35
|
+
return self
|
|
36
|
+
def setPixelScale(self, s=1):
|
|
37
|
+
self.renderWidth = None
|
|
38
|
+
self.renderHeight = None
|
|
39
|
+
self.pixelScale = s
|
|
40
|
+
return self
|
|
41
|
+
def calcRenderSize(self):
|
|
42
|
+
if self.renderWidth is None and self.renderHeight is None:
|
|
43
|
+
return (self.width * self.pixelScale,
|
|
44
|
+
self.height * self.pixelScale)
|
|
45
|
+
elif self.renderWidth is None:
|
|
46
|
+
s = self.renderHeight / self.height
|
|
47
|
+
return self.width * s, self.renderHeight
|
|
48
|
+
elif self.renderHeight is None:
|
|
49
|
+
s = self.renderWidth / self.width
|
|
50
|
+
return self.renderWidth, self.height * s
|
|
51
|
+
else:
|
|
52
|
+
return self.renderWidth, self.renderHeight
|
|
53
|
+
def draw(self, obj, **kwargs):
|
|
54
|
+
if not hasattr(obj, 'writeSvgElement'):
|
|
55
|
+
elements = obj.toDrawables(elements=elementsModule, **kwargs)
|
|
56
|
+
else:
|
|
57
|
+
assert len(kwargs) == 0
|
|
58
|
+
elements = (obj,)
|
|
59
|
+
self.extend(elements)
|
|
60
|
+
def append(self, element):
|
|
61
|
+
self.elements.append(element)
|
|
62
|
+
def extend(self, iterable):
|
|
63
|
+
self.elements.extend(iterable)
|
|
64
|
+
def insert(self, i, element):
|
|
65
|
+
self.elements.insert(i, element)
|
|
66
|
+
def remove(self, element):
|
|
67
|
+
self.elements.remove(element)
|
|
68
|
+
def clear(self):
|
|
69
|
+
self.elements.clear()
|
|
70
|
+
def index(self, *args, **kwargs):
|
|
71
|
+
self.elements.index(*args, **kwargs)
|
|
72
|
+
def count(self, element):
|
|
73
|
+
self.elements.count(element)
|
|
74
|
+
def reverse(self):
|
|
75
|
+
self.elements.reverse()
|
|
76
|
+
def drawDef(self, obj, **kwargs):
|
|
77
|
+
if not hasattr(obj, 'writeSvgElement'):
|
|
78
|
+
elements = obj.toDrawables(elements=elementsModule, **kwargs)
|
|
79
|
+
else:
|
|
80
|
+
assert len(kwargs) == 0
|
|
81
|
+
elements = (obj,)
|
|
82
|
+
self.otherDefs.extend(elements)
|
|
83
|
+
def appendDef(self, element):
|
|
84
|
+
self.otherDefs.append(element)
|
|
85
|
+
def asSvg(self, outputFile=None):
|
|
86
|
+
returnString = outputFile is None
|
|
87
|
+
if returnString:
|
|
88
|
+
outputFile = StringIO()
|
|
89
|
+
imgWidth, imgHeight = self.calcRenderSize()
|
|
90
|
+
startStr = '''<?xml version="1.0" encoding="UTF-8"?>
|
|
91
|
+
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
|
|
92
|
+
width="{}" height="{}" viewBox="{} {} {} {}"'''.format(
|
|
93
|
+
imgWidth, imgHeight, *self.viewBox)
|
|
94
|
+
endStr = '</svg>'
|
|
95
|
+
outputFile.write(startStr)
|
|
96
|
+
elementsModule.writeXmlNodeArgs(self.svgArgs, outputFile)
|
|
97
|
+
outputFile.write('>\n<defs>\n')
|
|
98
|
+
# Write definition elements
|
|
99
|
+
idIndex = 0
|
|
100
|
+
def idGen(base='d'):
|
|
101
|
+
nonlocal idIndex
|
|
102
|
+
idStr = base + str(idIndex)
|
|
103
|
+
idIndex += 1
|
|
104
|
+
return idStr
|
|
105
|
+
prevSet = set((id(defn) for defn in self.otherDefs))
|
|
106
|
+
def isDuplicate(obj):
|
|
107
|
+
nonlocal prevSet
|
|
108
|
+
dup = id(obj) in prevSet
|
|
109
|
+
prevSet.add(id(obj))
|
|
110
|
+
return dup
|
|
111
|
+
for element in self.otherDefs:
|
|
112
|
+
try:
|
|
113
|
+
element.writeSvgElement(outputFile)
|
|
114
|
+
outputFile.write('\n')
|
|
115
|
+
except AttributeError:
|
|
116
|
+
pass
|
|
117
|
+
for element in self.elements:
|
|
118
|
+
try:
|
|
119
|
+
element.writeSvgDefs(idGen, isDuplicate, outputFile)
|
|
120
|
+
except AttributeError:
|
|
121
|
+
pass
|
|
122
|
+
outputFile.write('</defs>\n')
|
|
123
|
+
# Write normal elements
|
|
124
|
+
for element in self.elements:
|
|
125
|
+
try:
|
|
126
|
+
element.writeSvgElement(outputFile)
|
|
127
|
+
outputFile.write('\n')
|
|
128
|
+
except AttributeError:
|
|
129
|
+
pass
|
|
130
|
+
outputFile.write(endStr)
|
|
131
|
+
if returnString:
|
|
132
|
+
return outputFile.getvalue()
|
|
133
|
+
def saveSvg(self, fname):
|
|
134
|
+
with open(fname, 'w') as f:
|
|
135
|
+
self.asSvg(outputFile=f)
|
|
136
|
+
def savePng(self, fname):
|
|
137
|
+
self.rasterize(toFile=fname)
|
|
138
|
+
def rasterize(self, toFile=None):
|
|
139
|
+
if toFile:
|
|
140
|
+
return Raster.fromSvgToFile(self.asSvg(), toFile)
|
|
141
|
+
else:
|
|
142
|
+
return Raster.fromSvg(self.asSvg())
|
|
143
|
+
def _repr_svg_(self):
|
|
144
|
+
''' Display in Jupyter notebook '''
|
|
145
|
+
return self.asSvg()
|
|
146
|
+
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
|
|
2
|
+
import sys
|
|
3
|
+
import math
|
|
4
|
+
import os.path
|
|
5
|
+
import base64
|
|
6
|
+
import warnings
|
|
7
|
+
import xml.sax.saxutils as xml
|
|
8
|
+
|
|
9
|
+
from . import defs
|
|
10
|
+
|
|
11
|
+
elementsModule = sys.modules[__name__]
|
|
12
|
+
|
|
13
|
+
# TODO: Support drawing ellipses without manually using Path
|
|
14
|
+
|
|
15
|
+
def writeXmlNodeArgs(args, outputFile):
|
|
16
|
+
for k, v in args.items():
|
|
17
|
+
if v is None: continue
|
|
18
|
+
k = k.replace('__', ':')
|
|
19
|
+
k = k.replace('_', '-')
|
|
20
|
+
if isinstance(v, defs.DrawingDef):
|
|
21
|
+
v = 'url(#{})'.format(v.id)
|
|
22
|
+
outputFile.write(' {}="{}"'.format(k,v))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class DrawingElement:
|
|
26
|
+
''' Base class for drawing elements
|
|
27
|
+
|
|
28
|
+
Subclasses must implement writeSvgElement '''
|
|
29
|
+
def writeSvgElement(self, outputFile):
|
|
30
|
+
raise NotImplementedError('Abstract base class')
|
|
31
|
+
def getSvgDefs(self):
|
|
32
|
+
return ()
|
|
33
|
+
def writeSvgDefs(self, idGen, isDuplicate, outputFile):
|
|
34
|
+
for defn in self.getSvgDefs():
|
|
35
|
+
if isDuplicate(defn): continue
|
|
36
|
+
defn.id = idGen()
|
|
37
|
+
defn.writeSvgElement(outputFile)
|
|
38
|
+
outputFile.write('\n')
|
|
39
|
+
def __eq__(self, other):
|
|
40
|
+
return self is other
|
|
41
|
+
|
|
42
|
+
class DrawingBasicElement(DrawingElement):
|
|
43
|
+
''' Base class for SVG drawing elements that are a single node with no
|
|
44
|
+
child nodes '''
|
|
45
|
+
TAG_NAME = '_'
|
|
46
|
+
hasContent = False
|
|
47
|
+
def __init__(self, **args):
|
|
48
|
+
self.args = args
|
|
49
|
+
@property
|
|
50
|
+
def id(self):
|
|
51
|
+
return self.args.get('id', None)
|
|
52
|
+
@id.setter
|
|
53
|
+
def id(self, newId):
|
|
54
|
+
self.args['id'] = newId
|
|
55
|
+
def writeSvgElement(self, outputFile):
|
|
56
|
+
outputFile.write('<')
|
|
57
|
+
outputFile.write(self.TAG_NAME)
|
|
58
|
+
writeXmlNodeArgs(self.args, outputFile)
|
|
59
|
+
if not self.hasContent:
|
|
60
|
+
outputFile.write(' />')
|
|
61
|
+
else:
|
|
62
|
+
outputFile.write('>')
|
|
63
|
+
self.writeContent(outputFile)
|
|
64
|
+
outputFile.write('</')
|
|
65
|
+
outputFile.write(self.TAG_NAME)
|
|
66
|
+
outputFile.write('>')
|
|
67
|
+
def writeContent(self, outputFile):
|
|
68
|
+
''' Override in a subclass to add data between the start and end
|
|
69
|
+
tags. This will not be called if hasContent is False. '''
|
|
70
|
+
raise RuntimeError('This element has no content')
|
|
71
|
+
def getSvgDefs(self):
|
|
72
|
+
return [v for v in self.args.values() if isinstance(v, defs.DrawingDef)]
|
|
73
|
+
def __eq__(self, other):
|
|
74
|
+
if isinstance(other, type(self)):
|
|
75
|
+
return (self.TAG_NAME == other.TAG_NAME and
|
|
76
|
+
self.args == other.args)
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
class DrawingParentElement(DrawingBasicElement):
|
|
80
|
+
''' Base class for SVG elements that can have child nodes '''
|
|
81
|
+
hasContent = True
|
|
82
|
+
def __init__(self, children=(), **args):
|
|
83
|
+
super().__init__(**args)
|
|
84
|
+
self.children = list(children)
|
|
85
|
+
if len(self.children) > 0:
|
|
86
|
+
self.checkChildrenAllowed()
|
|
87
|
+
def checkChildrenAllowed(self):
|
|
88
|
+
if not self.hasContent:
|
|
89
|
+
raise RuntimeError('{} does not support children'.format(type(self)))
|
|
90
|
+
def draw(self, obj, **kwargs):
|
|
91
|
+
if not hasattr(obj, 'writeSvgElement'):
|
|
92
|
+
elements = obj.toDrawables(elements=elementsModule, **kwargs)
|
|
93
|
+
self.extend(elements)
|
|
94
|
+
else:
|
|
95
|
+
assert len(kwargs) == 0
|
|
96
|
+
self.append(obj)
|
|
97
|
+
def append(self, element):
|
|
98
|
+
self.checkChildrenAllowed()
|
|
99
|
+
self.children.append(element)
|
|
100
|
+
def extend(self, iterable):
|
|
101
|
+
self.checkChildrenAllowed()
|
|
102
|
+
self.children.extend(iterable)
|
|
103
|
+
def writeContent(self, outputFile):
|
|
104
|
+
outputFile.write('\n')
|
|
105
|
+
for child in self.children:
|
|
106
|
+
child.writeSvgElement(outputFile)
|
|
107
|
+
outputFile.write('\n')
|
|
108
|
+
def writeSvgDefs(self, idGen, isDuplicate, outputFile):
|
|
109
|
+
super().writeSvgDefs(idGen, isDuplicate, outputFile)
|
|
110
|
+
for child in self.children:
|
|
111
|
+
child.writeSvgDefs(idGen, isDuplicate, outputFile)
|
|
112
|
+
|
|
113
|
+
class NoElement(DrawingElement):
|
|
114
|
+
''' A drawing element that has no effect '''
|
|
115
|
+
def __init__(self): pass
|
|
116
|
+
def writeSvgElement(self, outputFile):
|
|
117
|
+
pass
|
|
118
|
+
def __eq__(self, other):
|
|
119
|
+
if isinstance(other, type(self)):
|
|
120
|
+
return True
|
|
121
|
+
return False
|
|
122
|
+
|
|
123
|
+
class Group(DrawingParentElement):
|
|
124
|
+
''' A group of drawing elements
|
|
125
|
+
|
|
126
|
+
Any transform will apply to its children and other attributes will be
|
|
127
|
+
inherited by its children. '''
|
|
128
|
+
TAG_NAME = 'g'
|
|
129
|
+
|
|
130
|
+
class Use(DrawingBasicElement):
|
|
131
|
+
''' A copy of another element
|
|
132
|
+
|
|
133
|
+
Specify the other element by its id: href='#otherElemId'. '''
|
|
134
|
+
TAG_NAME = 'use'
|
|
135
|
+
def __init__(self, otherElem, x, y, **kwargs):
|
|
136
|
+
y = -y
|
|
137
|
+
if isinstance(otherElem, str):
|
|
138
|
+
otherElemId = otherElem
|
|
139
|
+
else:
|
|
140
|
+
if otherElem.id is None:
|
|
141
|
+
raise ValueError('otherElem must have an id')
|
|
142
|
+
otherElemId = otherElem.id
|
|
143
|
+
href = '#{}'.format(otherElemId)
|
|
144
|
+
super().__init__(xlink__href=href, x=x, y=y, **kwargs)
|
|
145
|
+
|
|
146
|
+
class Image(DrawingBasicElement):
|
|
147
|
+
''' A linked or embedded raster image '''
|
|
148
|
+
TAG_NAME = 'image'
|
|
149
|
+
MIME_MAP = {
|
|
150
|
+
'.bm': 'image/bmp',
|
|
151
|
+
'.bmp': 'image/bmp',
|
|
152
|
+
'.gif': 'image/gif',
|
|
153
|
+
'.jpeg':'image/jpeg',
|
|
154
|
+
'.jpg': 'image/jpeg',
|
|
155
|
+
'.png': 'image/png',
|
|
156
|
+
'.tif': 'image/tiff',
|
|
157
|
+
'.tiff':'image/tiff',
|
|
158
|
+
'.pdf': 'application/pdf',
|
|
159
|
+
'.txt': 'text/plain',
|
|
160
|
+
}
|
|
161
|
+
MIME_DEFAULT = 'image/png'
|
|
162
|
+
def __init__(self, x, y, width, height, path=None, data=None, embed=False,
|
|
163
|
+
mimeType=None, **kwargs):
|
|
164
|
+
''' Specify either the path or data argument. If path is used and
|
|
165
|
+
embed is True, the image file is embedded in a data URI. '''
|
|
166
|
+
if path is None and data is None:
|
|
167
|
+
raise ValueError('Either path or data arguments must be given')
|
|
168
|
+
if mimeType is None and path is not None:
|
|
169
|
+
ext = os.path.splitext(path)[1].lower()
|
|
170
|
+
if ext in self.MIME_MAP:
|
|
171
|
+
mimeType = self.MIME_MAP[ext]
|
|
172
|
+
else:
|
|
173
|
+
mimeType = self.MIME_DEFAULT
|
|
174
|
+
warnings.warn('Unknown image file type "{}"'.format(ext), Warning)
|
|
175
|
+
if mimeType is None:
|
|
176
|
+
mimeType = self.MIME_DEFAULT
|
|
177
|
+
warnings.warn('Unspecified image type; assuming png'.format(ext), Warning)
|
|
178
|
+
if data is not None:
|
|
179
|
+
embed = True
|
|
180
|
+
if embed and data is None:
|
|
181
|
+
with open(path, 'rb') as f:
|
|
182
|
+
data = f.read()
|
|
183
|
+
if not embed:
|
|
184
|
+
uri = path
|
|
185
|
+
else:
|
|
186
|
+
encData = base64.b64encode(data).decode()
|
|
187
|
+
uri = 'data:{};base64,{}'.format(mimeType, encData)
|
|
188
|
+
super().__init__(x=x, y=-y-height, width=width, height=height,
|
|
189
|
+
xlink__href=uri, **kwargs)
|
|
190
|
+
|
|
191
|
+
class Text(DrawingBasicElement):
|
|
192
|
+
''' Text
|
|
193
|
+
|
|
194
|
+
Additional keyword arguments are output as additional arguments to the
|
|
195
|
+
SVG node e.g. fill="red", font_size=20, text_anchor="middle". '''
|
|
196
|
+
TAG_NAME = 'text'
|
|
197
|
+
hasContent = True
|
|
198
|
+
def __init__(self, text, fontSize, x, y, center=False, **kwargs):
|
|
199
|
+
if center:
|
|
200
|
+
if 'text_anchor' not in kwargs:
|
|
201
|
+
kwargs['text_anchor'] = 'middle'
|
|
202
|
+
try:
|
|
203
|
+
fontSize = float(fontSize)
|
|
204
|
+
translate = 'translate(0,{})'.format(fontSize*0.5*center)
|
|
205
|
+
if 'transform' in kwargs:
|
|
206
|
+
kwargs['transform'] = translate + ' ' + kwargs['transform']
|
|
207
|
+
else:
|
|
208
|
+
kwargs['transform'] = translate
|
|
209
|
+
except TypeError:
|
|
210
|
+
pass
|
|
211
|
+
super().__init__(x=x, y=-y, font_size=fontSize, **kwargs)
|
|
212
|
+
self.escapedText = xml.escape(text)
|
|
213
|
+
def writeContent(self, outputFile):
|
|
214
|
+
outputFile.write(self.escapedText)
|
|
215
|
+
|
|
216
|
+
class Rectangle(DrawingBasicElement):
|
|
217
|
+
''' A rectangle
|
|
218
|
+
|
|
219
|
+
Additional keyword arguments are output as additional arguments to the
|
|
220
|
+
SVG node e.g. fill="red", stroke="#ff4477", stroke_width=2. '''
|
|
221
|
+
TAG_NAME = 'rect'
|
|
222
|
+
def __init__(self, x, y, width, height, **kwargs):
|
|
223
|
+
super().__init__(x=x, y=-y-height, width=width, height=height,
|
|
224
|
+
**kwargs)
|
|
225
|
+
|
|
226
|
+
class Circle(DrawingBasicElement):
|
|
227
|
+
''' A circle
|
|
228
|
+
|
|
229
|
+
Additional keyword arguments are output as additional properties to the
|
|
230
|
+
SVG node e.g. fill="red", stroke="#ff4477", stroke_width=2. '''
|
|
231
|
+
TAG_NAME = 'circle'
|
|
232
|
+
def __init__(self, cx, cy, r, **kwargs):
|
|
233
|
+
super().__init__(cx=cx, cy=-cy, r=r, **kwargs)
|
|
234
|
+
|
|
235
|
+
class ArcLine(Circle):
|
|
236
|
+
''' An arc
|
|
237
|
+
|
|
238
|
+
In most cases, use Arc instead of ArcLine. ArcLine uses the
|
|
239
|
+
stroke-dasharray SVG property to make the edge of a circle look like
|
|
240
|
+
an arc.
|
|
241
|
+
|
|
242
|
+
Additional keyword arguments are output as additional arguments to the
|
|
243
|
+
SVG node e.g. fill="red", stroke="#ff4477", stroke_width=2. '''
|
|
244
|
+
def __init__(self, cx, cy, r, startDeg, endDeg, **kwargs):
|
|
245
|
+
if endDeg - startDeg == 360:
|
|
246
|
+
super().__init__(cx, cy, r, **kwargs)
|
|
247
|
+
return
|
|
248
|
+
startDeg, endDeg = (-endDeg) % 360, (-startDeg) % 360
|
|
249
|
+
arcDeg = (endDeg - startDeg) % 360
|
|
250
|
+
def arcLen(deg): return math.radians(deg) * r
|
|
251
|
+
wholeLen = 2 * math.pi * r
|
|
252
|
+
if endDeg == startDeg:
|
|
253
|
+
offset = 1
|
|
254
|
+
dashes = "0 {}".format(wholeLen+2)
|
|
255
|
+
#elif endDeg >= startDeg:
|
|
256
|
+
elif True:
|
|
257
|
+
startLen = arcLen(startDeg)
|
|
258
|
+
arcLen = arcLen(arcDeg)
|
|
259
|
+
offLen = wholeLen - arcLen
|
|
260
|
+
offset = -startLen
|
|
261
|
+
dashes = "{} {}".format(arcLen, offLen)
|
|
262
|
+
#else:
|
|
263
|
+
# firstLen = arcLen(endDeg)
|
|
264
|
+
# secondLen = arcLen(360-startDeg)
|
|
265
|
+
# gapLen = wholeLen - firstLen - secondLen
|
|
266
|
+
# offset = 0
|
|
267
|
+
# dashes = "{} {} {}".format(firstLen, gapLen, secondLen)
|
|
268
|
+
super().__init__(cx, cy, r, stroke_dasharray=dashes,
|
|
269
|
+
stroke_dashoffset=offset, **kwargs)
|
|
270
|
+
|
|
271
|
+
class Path(DrawingBasicElement):
|
|
272
|
+
''' An arbitrary path
|
|
273
|
+
|
|
274
|
+
Path Supports building an SVG path by calling instance methods
|
|
275
|
+
corresponding to path commands.
|
|
276
|
+
|
|
277
|
+
Additional keyword arguments are output as additional properties to the
|
|
278
|
+
SVG node e.g. fill="red", stroke="#ff4477", stroke_width=2. '''
|
|
279
|
+
TAG_NAME = 'path'
|
|
280
|
+
def __init__(self, d='', **kwargs):
|
|
281
|
+
super().__init__(d=d, **kwargs)
|
|
282
|
+
def append(self, commandStr, *args):
|
|
283
|
+
if len(self.args['d']) > 0:
|
|
284
|
+
commandStr = ' ' + commandStr
|
|
285
|
+
if len(args) > 0:
|
|
286
|
+
commandStr = commandStr + ','.join(map(str, args))
|
|
287
|
+
self.args['d'] += commandStr
|
|
288
|
+
def M(self, x, y): self.append('M', x, -y)
|
|
289
|
+
def m(self, dx, dy): self.append('m', dx, -dy)
|
|
290
|
+
def L(self, x, y): self.append('L', x, -y)
|
|
291
|
+
def l(self, dx, dy): self.append('l', dx, -dy)
|
|
292
|
+
def H(self, x, y): self.append('H', x)
|
|
293
|
+
def h(self, dx): self.append('h', dx)
|
|
294
|
+
def V(self, y): self.append('V', -y)
|
|
295
|
+
def v(self, dy): self.append('v', -dy)
|
|
296
|
+
def Z(self): self.append('Z')
|
|
297
|
+
def C(self, cx1, cy1, cx2, cy2, ex, ey):
|
|
298
|
+
self.append('C', cx1, -cy1, cx2, -cy2, ex, -ey)
|
|
299
|
+
def c(self, cx1, cy1, cx2, cy2, ex, ey):
|
|
300
|
+
self.append('c', cx1, -cy1, cx2, -cy2, ex, -ey)
|
|
301
|
+
def S(self, cx2, cy2, ex, ey): self.append('S', cx2, -cy2, ex, -ey)
|
|
302
|
+
def s(self, cx2, cy2, ex, ey): self.append('s', cx2, -cy2, ex, -ey)
|
|
303
|
+
def Q(self, cx, cy, ex, ey): self.append('Q', cx, -cy, ex, -ey)
|
|
304
|
+
def q(self, cx, cy, ex, ey): self.append('q', cx, -cy, ex, -ey)
|
|
305
|
+
def T(self, ex, ey): self.append('T', ex, -ey)
|
|
306
|
+
def t(self, ex, ey): self.append('t', ex, -ey)
|
|
307
|
+
def A(self, rx, ry, rot, largeArc, sweep, ex, ey):
|
|
308
|
+
self.append('A', rx, ry, rot, int(bool(largeArc)), int(bool(sweep)), ex, -ey)
|
|
309
|
+
def a(self, rx, ry, rot, largeArc, sweep, ex, ey):
|
|
310
|
+
self.append('a', rx, ry, rot, int(bool(largeArc)), int(bool(sweep)), ex, -ey)
|
|
311
|
+
def arc(self, cx, cy, r, startDeg, endDeg, cw=False, includeM=True, includeL=False):
|
|
312
|
+
''' Uses A() to draw a circular arc '''
|
|
313
|
+
largeArc = (endDeg - startDeg) % 360 > 180
|
|
314
|
+
startRad, endRad = startDeg*math.pi/180, endDeg*math.pi/180
|
|
315
|
+
sx, sy = r*math.cos(startRad), r*math.sin(startRad)
|
|
316
|
+
ex, ey = r*math.cos(endRad), r*math.sin(endRad)
|
|
317
|
+
if includeL:
|
|
318
|
+
self.L(cx+sx, cy+sy)
|
|
319
|
+
elif includeM:
|
|
320
|
+
self.M(cx+sx, cy+sy)
|
|
321
|
+
self.A(r, r, 0, largeArc ^ cw, cw, cx+ex, cy+ey)
|
|
322
|
+
|
|
323
|
+
class Lines(Path):
|
|
324
|
+
''' A sequence of connected lines (or a polygon)
|
|
325
|
+
|
|
326
|
+
Additional keyword arguments are output as additional properties to the
|
|
327
|
+
SVG node e.g. fill="red", stroke="#ff4477", stroke_width=2. '''
|
|
328
|
+
def __init__(self, sx, sy, *points, close=False, **kwargs):
|
|
329
|
+
super().__init__(d='', **kwargs)
|
|
330
|
+
self.M(sx, sy)
|
|
331
|
+
assert len(points) % 2 == 0
|
|
332
|
+
for i in range(len(points) // 2):
|
|
333
|
+
self.L(points[2*i], points[2*i+1])
|
|
334
|
+
if close:
|
|
335
|
+
self.Z()
|
|
336
|
+
|
|
337
|
+
class Line(Lines):
|
|
338
|
+
''' A line
|
|
339
|
+
|
|
340
|
+
Additional keyword arguments are output as additional properties to the
|
|
341
|
+
SVG node e.g. fill="red", stroke="#ff4477", stroke_width=2. '''
|
|
342
|
+
def __init__(self, sx, sy, ex, ey, **kwargs):
|
|
343
|
+
super().__init__(sx, sy, ex, ey, close=False, **kwargs)
|
|
344
|
+
|
|
345
|
+
class Arc(Path):
|
|
346
|
+
''' An arc
|
|
347
|
+
|
|
348
|
+
Additional keyword arguments are output as additional properties to the
|
|
349
|
+
SVG node e.g. fill="red", stroke="#ff4477", stroke_width=2. '''
|
|
350
|
+
def __init__(self, cx, cy, r, startDeg, endDeg, cw=False, **kwargs):
|
|
351
|
+
super().__init__(d='', **kwargs)
|
|
352
|
+
self.arc(cx, cy, r, startDeg, endDeg, cw=cw, includeM=True)
|
|
353
|
+
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
|
|
2
|
+
import io
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
import cairosvg
|
|
6
|
+
except ImportError:
|
|
7
|
+
import warnings
|
|
8
|
+
from .missing import MissingModule
|
|
9
|
+
msg = 'CairoSVG will need to be install to rasterize images: Install with `pip3 install cairosvg`'
|
|
10
|
+
cairosvg = MissingModule(msg)
|
|
11
|
+
warnings.warn(msg, RuntimeWarning)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Raster:
|
|
15
|
+
def __init__(self, pngData=None, pngFile=None):
|
|
16
|
+
self.pngData = pngData
|
|
17
|
+
self.pngFile = pngFile
|
|
18
|
+
def savePng(self, fname):
|
|
19
|
+
with open(fname, 'wb') as f:
|
|
20
|
+
f.write(self.pngData)
|
|
21
|
+
@staticmethod
|
|
22
|
+
def fromSvg(svgData):
|
|
23
|
+
pngData = cairosvg.svg2png(bytestring=svgData)
|
|
24
|
+
return Raster(pngData)
|
|
25
|
+
@staticmethod
|
|
26
|
+
def fromSvgToFile(svgData, outFile):
|
|
27
|
+
cairosvg.svg2png(bytestring=svgData, write_to=outFile)
|
|
28
|
+
return Raster(None, pngFile=outFile)
|
|
29
|
+
def _repr_png_(self):
|
|
30
|
+
if self.pngData:
|
|
31
|
+
return self.pngData
|
|
32
|
+
elif self.pngFile:
|
|
33
|
+
try:
|
|
34
|
+
with open(self.pngFile, 'rb') as f:
|
|
35
|
+
return f.read()
|
|
36
|
+
except TypeError:
|
|
37
|
+
pass
|
|
38
|
+
try:
|
|
39
|
+
self.pngFile.seek(0)
|
|
40
|
+
return self.pngFile.read()
|
|
41
|
+
except io.UnsupportedOperation:
|
|
42
|
+
pass
|
|
43
|
+
|
drawSvg-1.0.0/setup.cfg
ADDED
drawSvg-1.0.0/setup.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from distutils.core import setup
|
|
2
|
+
|
|
3
|
+
setup(
|
|
4
|
+
name = 'drawSvg',
|
|
5
|
+
packages = ['drawSvg'],
|
|
6
|
+
version = '1.0.0',
|
|
7
|
+
description = 'This is a Python 3 library for programmatically generating SVG images (vector drawings) and rendering them or displaying them in an iPython notebook.',
|
|
8
|
+
author = 'Casey Duckering',
|
|
9
|
+
#author_email = '',
|
|
10
|
+
url = 'https://github.com/cduck/drawSvg',
|
|
11
|
+
download_url = 'https://github.com/cduck/drawSvg/archive/1.0.0.tar.gz',
|
|
12
|
+
keywords = ['SVG', 'draw', 'graphics', 'iPython', 'Jupyter'],
|
|
13
|
+
classifiers = [],
|
|
14
|
+
)
|
|
15
|
+
|