-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathdrawBotDrawingTools.py
More file actions
2609 lines (2164 loc) · 92.3 KB
/
drawBotDrawingTools.py
File metadata and controls
2609 lines (2164 loc) · 92.3 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AppKit
import CoreText
import Quartz
import math
import os
import tempfile
import random
import time
from collections import namedtuple
from .context import getContextForFileExt, getContextOptions, getFileExtensions, getContextOptionsDocs
from .context.baseContext import BezierPath, FormattedString, makeTextBoxes, getNSFontFromNameOrPath, getFontName
from .context.dummyContext import DummyContext
from .context.tools.imageObject import ImageObject
from .context.tools import gifTools
from .context.tools import openType
from .misc import DrawBotError, warnings, VariableController, optimizePath, isPDF, isEPS, isGIF, transformationAtCenter, clearMemoizeCache
def _getmodulecontents(module, names=None):
d = {}
if names is None:
names = [name for name in dir(module) if not name.startswith("_")]
for name in names:
d[name] = getattr(module, name)
return d
_paperSizes = {
'Letter' : (612, 792),
'LetterSmall' : (612, 792),
'Tabloid' : (792, 1224),
'Ledger' : (1224, 792),
'Legal' : (612, 1008),
'Statement' : (396, 612),
'Executive' : (540, 720),
'A0' : (2384, 3371),
'A1' : (1685, 2384),
'A2' : (1190, 1684),
'A3' : (842, 1190),
'A4' : (595, 842),
'A4Small' : (595, 842),
'A5' : (420, 595),
'B4' : (729, 1032),
'B5' : (516, 729),
'Folio' : (612, 936),
'Quarto' : (610, 780),
'10x14' : (720, 1008),
}
for key, (w, h) in list(_paperSizes.items()):
_paperSizes["%sLandscape" % key] = (h, w)
class SavedStateContextManager(object):
"""
Internal helper class for DrawBotDrawingTool.savedState() allowing 'with' notation:
with savedState()
translate(x, y)
...draw stuff...
"""
def __init__(self, drawingTools):
self._drawingTools = drawingTools
def __enter__(self):
self._drawingTools.save()
return self
def __exit__(self, type, value, traceback):
self._drawingTools.restore()
class DrawBotDrawingTool(object):
def __init__(self):
self._reset()
self._isSinglePage = False
def _get__all__(self):
return [i for i in dir(self) if not i.startswith("_")] + ["__version__"]
__all__ = property(_get__all__)
def _get_version(self):
try:
from drawBot import drawBotSettings
return drawBotSettings.__version__
except Exception:
pass
return ""
__version__ = property(_get_version)
def _addToNamespace(self, namespace):
namespace.update(_getmodulecontents(self, self.__all__))
namespace.update(_getmodulecontents(random, ["random", "randint", "choice", "shuffle"]))
namespace.update(_getmodulecontents(math))
def _addInstruction(self, callback, *args, **kwargs):
if callback == "newPage":
self._instructionsStack.append([])
if not self._instructionsStack:
self._instructionsStack.append([])
if self._requiresNewFirstPage and not self._hasPage:
self._hasPage = True
self._instructionsStack[-1].insert(0, ("newPage", [self.width(), self.height()], {}))
self._instructionsStack[-1].append((callback, args, kwargs))
def _drawInContext(self, context):
if not self._instructionsStack:
return
for instructionSet in self._instructionsStack:
for callback, args, kwargs in instructionSet:
attr = getattr(context, callback)
attr(*args, **kwargs)
def _reset(self, other=None):
if other is not None:
self._instructionsStack = list(other._instructionsStack)
self._dummyContext = other._dummyContext
self._width = other._width
self._height = other._height
self._tempInstalledFonts = dict(other._tempInstalledFonts)
self._requiresNewFirstPage = other._requiresNewFirstPage
self._hasPage = other._hasPage
else:
self._instructionsStack = []
self._dummyContext = DummyContext()
self._width = None
self._height = None
self._requiresNewFirstPage = False
self._hasPage = False
if not hasattr(self, "_tempInstalledFonts"):
self._tempInstalledFonts = dict()
self._cachedPixelColorBitmaps = {}
clearMemoizeCache()
def _copy(self):
new = self.__class__()
new._instructionsStack = list(self._instructionsStack)
new._dummyContext = self._dummyContext
new._width = self._width
new._height = self._height
new._hasPage = self._hasPage
new._requiresNewFirstPage = self._requiresNewFirstPage
new._tempInstalledFonts = dict(self._tempInstalledFonts)
return new
def newDrawing(self):
"""
Reset the drawing stack to the clean and empty stack.
.. downloadcode:: newDrawing.py
# draw a rectangle
rect(10, 10, width()-20, height()-20)
# save it as a pdf
saveImage("~/Desktop/aRect.pdf")
# reset the drawing stack to a clear and empty stack
newDrawing()
# draw an oval
oval(10, 10, width()-20, height()-20)
# save it as a pdf
saveImage("~/Desktop/anOval.pdf")
"""
self._reset()
def endDrawing(self):
"""
Explicitly tell drawBot the drawing is done.
This is advised when using drawBot as a standalone module.
"""
self._uninstallAllFonts()
gifTools.clearExplodedGifCache()
# magic variables
def width(self):
"""
Returns the width of the current page.
"""
if self._width is None:
return 1000
return self._width
def height(self):
"""
Returns the height of the current page.
"""
if self._height is None:
return 1000
return self._height
def sizes(self, paperSize=None):
"""
Returns the width and height of a specified canvas size.
If no canvas size is given it will return the dictionary containing all possible page sizes.
"""
_paperSizes["screen"] = tuple(AppKit.NSScreen.mainScreen().frame().size)
if paperSize:
return _paperSizes[paperSize]
return _paperSizes
def pageCount(self):
"""
Returns the current page count.
"""
return len(self._instructionsStack)
# ====================
# = public callbacks =
# ====================
# size and pages
def size(self, width, height=None):
"""
Set the width and height of the canvas.
Without calling `size()` the default drawing board is 1000 by 1000 points.
Alternatively `size('A4')` with a supported papersizes or `size('screen')` setting the current screen size as size, can be used.
Afterwards the functions `width()` and `height()` can be used for calculations.
You have to use `size()` before any drawing-related code, and you can't use `size()`
in a multi-page document. Use `newPage(w, h)` to set the correct dimensions for each page.
.. downloadcode:: size.py
# set a canvas size
size(200, 200)
# print out the size of the page
print((width(), height()))
# set a color
fill(1, 0, 0)
# use those variables to set a background color
rect(0, 0, width(), height())
All supported papersizes: 10x14, 10x14Landscape, A0, A0Landscape, A1, A1Landscape, A2, A2Landscape, A3, A3Landscape, A4, A4Landscape, A4Small, A4SmallLandscape, A5, A5Landscape, B4, B4Landscape, B5, B5Landscape, Executive, ExecutiveLandscape, Folio, FolioLandscape, Ledger, LedgerLandscape, Legal, LegalLandscape, Letter, LetterLandscape, LetterSmall, LetterSmallLandscape, Quarto, QuartoLandscape, Statement, StatementLandscape, Tabloid, TabloidLandscape.
"""
if self._isSinglePage:
# dont allow to set a page size
raise DrawBotError("Cannot set 'size' into a single page.")
if width in _paperSizes:
width, height = _paperSizes[width]
if width == "screen":
width, height = AppKit.NSScreen.mainScreen().frame().size
if height is None:
width, height = width
self._width = width
self._height = height
if not self._instructionsStack:
self.newPage(width, height)
else:
raise DrawBotError("Can't use 'size()' after drawing has begun. Try to move it to the top of your script.")
def newPage(self, width=None, height=None):
"""
Create a new canvas to draw in.
This will act like a page in a pdf or a frame in a mov.
Optionally a `width` and `height` argument can be provided to set the size.
If not provided the default size will be used.
Alternatively `size('A4')` with a supported papersizes or `size('screen')` setting the current screen size as size, can be used.
.. downloadcode:: newPage.py
# loop over a range of 100
for i in range(100):
# for each loop create a new path
newPage(500, 500)
# set a random fill color
fill(random(), random(), random())
# draw a rect with the size of the page
rect(0, 0, width(), height())
All supported papersizes: 10x14, 10x14Landscape, A0, A0Landscape, A1, A1Landscape, A2, A2Landscape, A3, A3Landscape, A4, A4Landscape, A4Small, A4SmallLandscape, A5, A5Landscape, B4, B4Landscape, B5, B5Landscape, Executive, ExecutiveLandscape, Folio, FolioLandscape, Ledger, LedgerLandscape, Legal, LegalLandscape, Letter, LetterLandscape, LetterSmall, LetterSmallLandscape, Quarto, QuartoLandscape, Statement, StatementLandscape, Tabloid, TabloidLandscape.
"""
if self._isSinglePage:
# dont allow to add a page
raise DrawBotError("Cannot add a 'newPage' into a single page.")
if width in _paperSizes:
width, height = _paperSizes[width]
if width == "screen":
width, height = AppKit.NSScreen.mainScreen().frame().size
if width is None and height is None:
width = self.width()
height = self.height()
self._width = width
self._height = height
self._hasPage = True
self._dummyContext = DummyContext()
self._addInstruction("newPage", width, height)
def pages(self):
"""
Return all pages.
.. downloadcode:: pages.py
# set a size
size(200, 200)
# draw a rectangle
rect(10, 10, 100, 100)
# create a new page
newPage(200, 300)
# set a color
fill(1, 0, 1)
# draw a rectangle
rect(10, 10, 100, 100)
# create a new page
newPage(200, 200)
# set a color
fill(0, 1, 0)
# draw a rectangle
rect(10, 10, 100, 100)
# get all pages
allPages = pages()
# count how many pages are available
print(len(allPages))
# use the `with` statement
# to set a page as current context
with allPages[1]:
# draw into the selected page
fontSize(30)
text("Hello World", (10, 150))
# loop over allpages
for page in allPages:
# set the page as current context
with page:
# draw an oval in each of them
oval(110, 10, 30, 30)
"""
from .drawBotPageDrawingTools import DrawBotPage
instructions = []
for instructionSet in self._instructionsStack:
for callback, _, _ in instructionSet:
if callback == "newPage":
instructions.append(instructionSet)
break
return tuple(DrawBotPage(instructionSet) for instructionSet in instructions)
def saveImage(self, path, *args, **options):
"""
Save or export the canvas to a specified format.
The `path` argument is a single destination path to save the current drawing actions.
The file extension is important because it will determine the format in which the image will be exported.
All supported file extensions: %(supporttedExtensions)s.
(`*` will print out all actions.)
When exporting an animation or movie, each page represents a frame and the framerate is set by calling `frameDuration()` after each `newPage()`.
.. downloadcode:: saveImage.py
# set the canvas size
size(150, 100)
# draw a background
rect(10, 10, width()-20, height()-20)
# set a fill
fill(1)
# draw some text
text("Hello World!", (20, 40))
# save it as a png and pdf on the current users desktop
saveImage("~/Desktop/firstImage.png")
saveImage("~/Desktop/firstImage.pdf")
`saveImage()` options can be set by adding keyword arguments. Which options are recognized
depends on the output format.
%(supportedOptions)s
.. downloadcode:: saveImageResolutionExample.py
# same example but we just change the image resolution
size(150, 100)
rect(10, 10, width()-20, height()-20)
fill(1)
text("Hello World!", (20, 40))
# save it with an option that controls the resolution (300 PPI)
saveImage("~/Desktop/firstImage300.png", imageResolution=300)
"""
if not isinstance(path, (str, os.PathLike)):
raise TypeError("Cannot apply saveImage options to multiple output formats, expected 'str' or 'os.PathLike', got '%s'" % type(path).__name__)
# args are not supported anymore
if args:
if len(args) == 1:
# if there is only 1 is the old multipage
warnings.warn("'multipage' should be a keyword argument: use 'saveImage(path, multipage=True)'")
options["multipage"] = args[0]
else:
# if there are more just raise a TypeError
raise TypeError("saveImage(path, **options) takes only keyword arguments")
originalPath = path
path = optimizePath(path)
dirName = os.path.dirname(path)
if not os.path.exists(dirName):
raise DrawBotError("Folder '%s' doesn't exists" % dirName)
base, ext = os.path.splitext(path)
ext = ext.lower()[1:]
if not ext:
path = ext = originalPath
context = getContextForFileExt(ext)
if context is None:
raise DrawBotError("Could not find a supported context for: '%s'" % ext)
if context.validateSaveImageOptions:
allowedSaveImageOptions = set(optionName for optionName, optionDoc in context.saveImageOptions)
for optionName in options:
if optionName not in allowedSaveImageOptions:
warnings.warn("Unrecognized saveImage() option found for %s: %s" % (context.__class__.__name__, optionName))
self._drawInContext(context)
return context.saveImage(path, options)
# filling docs with content from all possible and installed contexts
saveImage.__doc__ = saveImage.__doc__ % dict(
supporttedExtensions="`%s`" % "`, `".join(getFileExtensions()),
supportedOptions="\n ".join(getContextOptionsDocs())
)
def printImage(self, pdf=None):
"""
Export the canvas to a printing dialog, ready to print.
Optionally a `pdf` object can be provided.
.. downloadcode:: printImage.py
# set A4 page size
size(595, 842)
# draw something
oval(0, 0, width(), height())
# send it to the printer
printImage()
"""
context = getContextForFileExt("pdf")
if pdf is None:
self._drawInContext(context)
context.printImage()
else:
context.printImage(pdf)
def pdfImage(self):
"""
Return the image as a pdf document object.
"""
from .context.drawBotContext import DrawBotContext
context = DrawBotContext()
self._drawInContext(context)
return context.getNSPDFDocument()
def shareImage(self, format="pdf", service="airdrop", **kwargs):
"""
Share the canvas to a service with a specified format.
As default the `format` is `pdf`, any suffix drawBot supports is possible.
`service` options are `airdrop`, `mail` or `message`.
.. downloadcode:: shareImage.py
# set A4 page size
newPage(200, 200)
# draw something
text("Foo, bar", (10, 10))
# share it over airdrop
shareImage('pdf', service="airdrop")
"""
class SharingServiceDelegate:
def __init__(self, path):
self.path = path
def _removePath(self):
if os.path.exists(self.path):
os.remove(self.path)
def sharingService_didShareItems_(self, sharingService, items):
# wait a sec to be sure the serice (like mail) has started up
# and collected all the assets from disk
time.sleep(1)
self._removePath()
def sharingService_didFailToShareItems_error_(self, sharingService, items, error):
self._removePath()
serviceMap = dict(
airdrop=AppKit.NSSharingServiceNameSendViaAirDrop,
mail=AppKit.NSSharingServiceNameComposeEmail,
message=AppKit.NSSharingServiceNameComposeMessage,
)
if service not in serviceMap:
raise DrawBotError(f"service must be {', '.join(serviceMap.keys())}")
path = tempfile.mkstemp(suffix=f".{format}")[1]
self.saveImage(path, **kwargs)
if os.path.exists(path):
# only pop up the sharing service when saveImage is succes full
sharingService = AppKit.NSSharingService.sharingServiceNamed_(serviceMap[service])
sharingService.setDelegate_(SharingServiceDelegate(path))
sharingService.performWithItems_([
AppKit.NSURL.fileURLWithPath_(path)
])
# graphics state
def save(self):
"""
DrawBot strongly recommends to use `savedState()` in a `with` statement instead.
Save the current graphics state.
This will save the state of the canvas (with all the transformations)
but also the state of the colors, strokes...
"""
self._dummyContext.save()
self._requiresNewFirstPage = True
self._addInstruction("save")
def restore(self):
"""
DrawBot strongly recommends to use `savedState()` in a `with` statement instead.
Restore from a previously saved graphics state.
This will restore the state of the canvas (with all the transformations)
but also the state of colors, strokes...
"""
self._dummyContext.restore()
self._requiresNewFirstPage = True
self._addInstruction("restore")
def savedState(self):
"""
Save and restore the current graphics state in a `with` statement.
.. downloadcode:: savedState.py
# Use the 'with' statement.
# This makes any changes you make to the graphics state -- such as
# colors and transformations -- temporary, and will be reset to
# the previous state at the end of the 'with' block.
with savedState():
# set a color
fill(1, 0, 0)
# do a transformation
translate(450, 50)
rotate(45)
# draw something
rect(0, 0, 700, 600)
# already returned to the previously saved graphics state
# so this will be a black rectangle
rect(0, 0, 50, 50)
"""
return SavedStateContextManager(self)
# basic shapes
def rect(self, x, y, w, h):
"""
Draw a rectangle from position x, y with the given width and height.
.. downloadcode:: rect.py
# draw a rectangle
# x y w h
rect(100, 100, 800, 800)
"""
self._requiresNewFirstPage = True
self._addInstruction("rect", x, y, w, h)
def oval(self, x, y, w, h):
"""
Draw an oval from position x, y with the given width and height.
.. downloadcode:: oval.py
# draw an oval
# x y w h
oval(100, 100, 800, 800)
"""
self._requiresNewFirstPage = True
self._addInstruction("oval", x, y, w, h)
# path
def newPath(self):
"""
Create a new path.
"""
self._requiresNewFirstPage = True
self._addInstruction("newPath")
def moveTo(self, xy):
"""
Move to a point `x`, `y`.
"""
x, y = xy
self._requiresNewFirstPage = True
self._addInstruction("moveTo", (x, y))
def lineTo(self, xy):
"""
Line to a point `x`, `y`.
"""
x, y = xy
self._requiresNewFirstPage = True
self._addInstruction("lineTo", (x, y))
def curveTo(self, xy1, xy2, xy3):
"""
Curve to a point `x3`, `y3`.
With given bezier handles `x1`, `y1` and `x2`, `y2`.
"""
x1, y1 = xy1
x2, y2 = xy2
x3, y3 = xy3
self._requiresNewFirstPage = True
self._addInstruction("curveTo", (x1, y1), (x2, y2), (x3, y3))
def qCurveTo(self, *points):
"""
Quadratic curve with a given set of off curves to a on curve.
"""
self._requiresNewFirstPage = True
self._addInstruction("qCurveTo", points)
def arc(self, center, radius, startAngle, endAngle, clockwise):
"""
Arc with `center` and a given `radius`, from `startAngle` to `endAngle`, going clockwise if `clockwise` is True and counter clockwise if `clockwise` is False.
"""
self._requiresNewFirstPage = True
self._addInstruction("arc", center, radius, startAngle, endAngle, clockwise)
def arcTo(self, xy1, xy2, radius):
"""
Arc from one point to an other point with a given `radius`.
.. downloadcode:: arcTo-example.py
pt0 = 74, 48
pt1 = 238, 182
pt2 = 46, 252
radius = 60
def drawPt(pos, r=5):
x, y = pos
oval(x-r, y-r, r*2, r*2)
size(300, 300)
fill(None)
path = BezierPath()
path.moveTo(pt0)
path.arcTo(pt1, pt2, radius)
stroke(0, 1, 1)
polygon(pt0, pt1, pt2)
for pt in [pt0, pt1, pt2]:
drawPt(pt)
stroke(0, 0, 1)
drawPath(path)
stroke(1, 0, 1)
for pt in path.onCurvePoints:
drawPt(pt, r=3)
for pt in path.offCurvePoints:
drawPt(pt, r=2)
"""
x1, y1 = xy1
x2, y2 = xy2
self._requiresNewFirstPage = True
self._addInstruction("arcTo", (x1, y1), (x2, y2), radius)
def closePath(self):
"""
Close the path.
"""
self._requiresNewFirstPage = True
self._addInstruction("closePath")
def drawPath(self, path=None):
"""
Draw the current path, or draw the provided path.
.. downloadcode:: drawPath.py
# create a new empty path
newPath()
# set the first oncurve point
moveTo((100, 100))
# line to from the previous point to a new point
lineTo((100, 900))
lineTo((900, 900))
# curve to a point with two given handles
curveTo((900, 500), (500, 100), (100, 100))
# close the path
closePath()
# draw the path
drawPath()
"""
if isinstance(path, AppKit.NSBezierPath):
path = self._bezierPathClass(path)
if isinstance(path, self._bezierPathClass):
path = path.copy()
self._requiresNewFirstPage = True
self._addInstruction("drawPath", path)
def clipPath(self, path=None):
"""
Use the given path as a clipping path, or the current path if no path was given.
Everything drawn after a `clipPath()` call will be clipped by the clipping path.
To "undo" the clipping later, make sure you do the clipping inside a
`with savedState():` block, as shown in the example.
.. downloadcode:: clipPath.py
# create a bezier path
path = BezierPath()
# draw a triangle
# move to a point
path.moveTo((100, 100))
# line to a point
path.lineTo((100, 900))
path.lineTo((900, 900))
# close the path
path.closePath()
# save the graphics state so the clipping happens only
# temporarily
with savedState():
# set the path as a clipping path
clipPath(path)
# the oval will be clipped inside the path
oval(100, 100, 800, 800)
# no more clipping here
"""
self._requiresNewFirstPage = True
self._addInstruction("clipPath", path)
def line(self, point1, point2):
"""
Draws a line between two given points.
.. downloadcode:: line.py
# set a stroke color
stroke(0)
# draw a line between two given points
line((100, 100), (900, 900))
"""
path = self._bezierPathClass()
path.line(point1, point2)
self.drawPath(path)
def polygon(self, *points, **kwargs):
"""
Draws a polygon with n-amount of points.
Optionally a `close` argument can be provided to open or close the path.
As default a `polygon` is a closed path.
.. downloadcode:: polygon.py
# draw a polygon with x-amount of points
polygon((100, 100), (100, 900), (900, 900), (200, 800), close=True)
"""
path = self._bezierPathClass()
path.polygon(*points, **kwargs)
self.drawPath(path)
# color
def colorSpace(self, colorSpace):
"""
Set the color space.
Options are `genericRGB`, `adobeRGB1998`, `sRGB`, `genericGray`, `genericGamma22Gray`.
The default is `genericRGB`.
`None` will reset it back to the default.
.. downloadcode:: colorSpace.py
# set a color
r, g, b, a = 0.74, 0.51, 1.04, 1
# get all available color spaces
colorSpaces = listColorSpaces()
x = 0
w = width() / len(colorSpaces)
# start loop
for space in colorSpaces:
# set a color space
colorSpace(space)
# set the color
fill(r, g, b)
# draw a rect
rect(x, 0, w, height())
x += w
"""
self._requiresNewFirstPage = True
self._addInstruction("colorSpace", colorSpace)
def listColorSpaces(self):
"""
Return a list of all available color spaces.
"""
return sorted(self._dummyContext._colorSpaceMap.keys())
def blendMode(self, operation):
"""
Set a blend mode.
Available operations are: `normal`, `multiply`, `screen`, `overlay`,
`darken`, `lighten`, `colorDodge`, `colorBurn`, `softLight`,
`hardLight`, `difference`, `exclusion`, `hue`, `saturation`,
`color`, `luminosity`, `clear`, `copy`, `sourceIn`, `sourceOut`,
`sourceAtop`, `destinationOver`, `destinationIn`, `destinationOut`,
`destinationAtop`, `xOR`, `plusDarker` and `plusLighter`,
.. downloadcode:: blendMode.py
# set a blend mode
blendMode("multiply")
# set a color
cmykFill(1, 0, 0, 0)
# draw a rectangle
rect(10, 10, 600, 600)
# set an other color
cmykFill(0, 1, 0, 0)
# overlap a second rectangle
rect(390, 390, 600, 600)
"""
if operation not in self._dummyContext._blendModeMap.keys():
raise DrawBotError("blend mode must be %s" % (", ".join(self._dummyContext._blendModeMap.keys())))
self._requiresNewFirstPage = True
self._addInstruction("blendMode", operation)
def fill(self, r=None, g=None, b=None, alpha=1):
"""
Sets the fill color with a `red`, `green`, `blue` and `alpha` value.
Each argument must a value float between 0 and 1.
.. downloadcode:: fill.py
fill(1, 0, 0, .5)
# draw a rect
rect(10, 10, 200, 980)
# only set a gray value
fill(0)
# draw a rect
rect(200, 10, 200, 980)
# only set a gray value with an alpha
fill(0, .5)
# draw a rect
rect(400, 10, 200, 980)
# set rgb with no alpha
fill(1, 0, 0)
# draw a rect
rect(600, 10, 200, 980)
# set rgb with an alpha value
fill(1, 0, 0, .5)
# draw a rect
rect(800, 10, 190, 980)
"""
self._requiresNewFirstPage = True
self._addInstruction("fill", r, g, b, alpha)
def stroke(self, r=None, g=None, b=None, alpha=1):
"""
Sets the stroke color with a `red`, `green`, `blue` and `alpha` value.
Each argument must a value float between 0 and 1.
.. downloadcode:: stroke.py
# set the fill to none
fill(None)
# set a stroke width
stroke(1, 0, 0, .3)
strokeWidth(10)
# draw a rect
rect(10, 10, 180, 980)
# only set a gray value
stroke(0)
# draw a rect
rect(210, 10, 180, 980)
# only set a gray value with an alpha
stroke(0, .5)
# draw a rect
rect(410, 10, 180, 980)
# set rgb with no alpha
stroke(1, 0, 0)
# draw a rect
rect(610, 10, 180, 980)
# set rgb with an alpha value
stroke(1, 0, 0, .5)
# draw a rect
rect(810, 10, 180, 980)
"""
self._requiresNewFirstPage = True
self._addInstruction("stroke", r, g, b, alpha)
def cmykFill(self, c, m=None, y=None, k=None, alpha=1):
"""
Set a fill using a CMYK color before drawing a shape. This is handy if the file is intended for print.
Sets the CMYK fill color. Each value must be a float between 0.0 and 1.0.
.. downloadcode:: cmykFill.py
# cyan
cmykFill(1, 0, 0, 0)
rect(0, 0, 250, 1000)
# magenta
cmykFill(0, 1, 0, 0)
rect(250, 0, 250, 1000)
# yellow
cmykFill(0, 0, 1, 0)
rect(500, 0, 250, 1000)
# black
cmykFill(0, 0, 0, 1)
rect(750, 0, 250, 1000)
"""
self._requiresNewFirstPage = True
self._addInstruction("cmykFill", c, m, y, k, alpha)
def cmykStroke(self, c, m=None, y=None, k=None, alpha=1):
"""
Set a stroke using a CMYK color before drawing a shape. This is handy if the file is intended for print.
Sets the CMYK stroke color. Each value must be a float between 0.0 and 1.0.
.. downloadcode:: cmykStroke.py
# define x, y and the amount of lines needed
x, y = 20, 20
lines = 49
# calculate the smallest step
colorStep = 1.00 / lines
# set stroke width
strokeWidth(10)
# start a loop
for i in range(lines):
# set a cmyk color
# the magenta value is calculated
cmykStroke(0, i * colorStep, 1, 0)
# draw a line
line((x, y), (x, y + 960))
# translate the canvas
translate(20, 0)
"""
self._requiresNewFirstPage = True
self._addInstruction("cmykStroke", c, m, y, k, alpha)
def shadow(self, offset, blur=None, color=None):
"""
Adds a shadow with an `offset` (x, y), `blur` and a `color`.
The `color` argument must be a tuple similarly as `fill`.
The `offset`and `blur` argument will be drawn independent of the current context transformations.
.. downloadcode:: shadow.py
# a red shadow with some blur and a offset
shadow((100, 100), 100, (1, 0, 0))
# draw a rect
rect(100, 100, 600, 600)
"""
if color is None:
color = (0, 0, 0)
if blur is None:
blur = 10
self._requiresNewFirstPage = True
self._addInstruction("shadow", offset, blur, color)