예제 #1
0
 def makeTestICNSDrawing(self, formats):
     drawBot.newDrawing()
     for i, size in enumerate(formats):
         drawBot.newPage(size, size)
         f = i / (len(formats) + 1)
         drawBot.fill(f, f, 1 - f)
         drawBot.rect(0, 0, size, size)
예제 #2
0
 def run(self, render_pass, renderer_state):
     use_pool = True
     if use_pool:
         pool = AppKit.NSAutoreleasePool.alloc().init()
     try:
         db.newDrawing()
         if renderer_state.previewing:
             ps = renderer_state.preview_scale
             db.size(self.rect.w * ps, self.rect.h * ps)
             db.scale(ps, ps)
             DATPen().rect(self.rect).f(self.bg).db_drawPath()
         else:
             db.size(self.rect.w, self.rect.h)
         render_pass.fn(*render_pass.args)
         result = None
         if renderer_state.previewing:
             previews = (render_pass.output_path.parent / "_previews")
             previews.mkdir(exist_ok=True, parents=True)
             preview_frame = previews / render_pass.output_path.name
             db.saveImage(str(preview_frame))
             result = preview_frame
         else:
             render_pass.output_path.parent.mkdir(exist_ok=True,
                                                  parents=True)
             db.saveImage(str(render_pass.output_path))
             result = render_pass.output_path
         db.endDrawing()
     finally:
         if use_pool:
             del pool
     return result
예제 #3
0
 def test_fontVariations(self):
     drawBot.newDrawing()
     var = drawBot.listFontVariations()
     self.assertEqual(var, {})
     drawBot.font("Skia")
     # get the default font variations
     var = drawBot.listFontVariations()
     var['wght'] = _roundDictValues(var['wght'], 3)
     var['wdth'] = _roundDictValues(var['wdth'], 3)
     expectedVar = OrderedDict({
         'wght': {'name': 'Weight', 'minValue': 0.48, 'maxValue': 3.2, 'defaultValue': 1.0},
         'wdth': {'name': 'Width', 'minValue': 0.62, 'maxValue': 1.3, 'defaultValue': 1.0},
     })
     self.assertEqual(var, expectedVar)
     # set a font variation
     var = drawBot.fontVariations(wght=5)
     expectedVarChanged = {'wght': 5, 'wdth': 1.0}
     self.assertEqual(var, expectedVarChanged)
     # clear all font variations settings
     var = drawBot.fontVariations(resetVariations=True)
     self.assertEqual(var, {'wght': 1.0, 'wdth': 1.0})
     drawBot.font("Helvetica")
     var = drawBot.listFontVariations()
     self.assertEqual(var, {})
     var = drawBot.fontVariations(wght=5)
     self.assertEqual(var, {"wght": 5})
예제 #4
0
파일: testMisc.py 프로젝트: sahwar/drawbot
 def test_newPage_following(self):
     drawBot.newDrawing()
     drawBot.size(400, 500)
     drawBot.newPage()
     self.assertEqual(drawBot.width(), 400)
     self.assertEqual(drawBot.height(), 500)
     self.assertEqual(drawBot.pageCount(), 2)
예제 #5
0
 def test_polygon_notEnoughPoints(self):
     drawBot.newDrawing()
     with self.assertRaises(TypeError):
         drawBot.polygon()
     with self.assertRaises(TypeError):
         drawBot.polygon((1, 2))
     drawBot.polygon((1, 2), (3, 4))
예제 #6
0
 def test_newPage_following(self):
     drawBot.newDrawing()
     drawBot.size(400, 500)
     drawBot.newPage()
     self.assertEqual(drawBot.width(), 400)
     self.assertEqual(drawBot.height(), 500)
     self.assertEqual(drawBot.pageCount(), 2)
    def draw(self):
        self.xFactor = self.targetXheight / currentXheight

        drawBot.newDrawing()
        drawBot.newPage("LetterLandscape")

        pageWidth = drawBot.width()

        drawBot.fill(0, 0, 0, 0.5)
        drawBot.stroke(0, 0, 0, 1)

        drawBot.rect(.5 * dpi, .5 * dpi, pageWidth - (1 * dpi),
                     self.targetXheight)

        drawBot.translate(0.5 * dpi, .5 * dpi)
        drawBot.scale(self.xFactor)

        for g in self.text:
            pen = CocoaPen(f)
            f[g].draw(pen)
            drawBot.drawPath(pen.path)
            drawBot.translate(f[g].width, 0)

        pdf = drawBot.pdfImage()
        # set the pdf data in the canvas
        self.w.canvas.setPDFDocument(pdf)
예제 #8
0
    def test(self):
        from drawBot.drawBotDrawingTools import _drawBotDrawingTool

        code = compile(source, "<%s>" % exampleName, "exec")

        namespace = {}
        _drawBotDrawingTool._addToNamespace(namespace)

        def mockSaveImage(path, **options):
            fileName = "example_mockSaveImage_" + os.path.basename(path)
            path = os.path.join(tempTestDataDir, fileName)
            drawBot.saveImage(path, **options)

        namespace["saveImage"] = mockSaveImage
        namespace["image"] = mockImage
        namespace["imageSize"] = mockImageSize
        namespace["imagePixelColor"] = mockImagePixelColor
        namespace["Variable"] = mockVariable
        namespace["printImage"] = mockPrintImage
        namespace["installFont"] = mockInstallFont
        namespace["uninstallFont"] = mockUninstallFont
        namespace["randint"] = mockRandInt

        randomSeed(0)
        drawBot.newDrawing()
        with StdOutCollector(captureStdErr=True):
            exec(code, namespace)
        fileName = "example_%s.png" % exampleName
        imagePath = os.path.join(tempTestDataDir, fileName)
        expectedImagePath = os.path.join(testDataDir, fileName)
        if doSaveImage:
            drawBot.saveImage(imagePath)
            self.assertImagesSimilar(imagePath, expectedImagePath)
예제 #9
0
 def test(self):
     # get the paths
     testPath = os.path.join(tempTestDataDir, "%s.%s" % (scriptName, ext))
     expectedPath = os.path.join(testDataDir,
                                 "expected_%s.%s" % (scriptName, ext))
     expectedOutputPath = os.path.join(testDataDir,
                                       "expected_%s.txt" % scriptName)
     expectedOutput = readExpectedOutput(expectedOutputPath)
     # get drawBot
     import drawBot
     # start a new drawing
     drawBot.newDrawing()
     # execute the script in place
     # temporarily ignore deprecation warnings (there are some from PyObjC :( )
     with warnings.catch_warnings():
         if ignoreDeprecationWarnings:
             warnings.simplefilter("ignore", DeprecationWarning)
         output = self.executeScriptPath(path)
     self.assertEqual(cleanupTraceback(output),
                      cleanupTraceback(expectedOutput))
     # save the image
     drawBot.saveImage(testPath)
     # tell drawBot drawing is done
     drawBot.endDrawing()
     self.assertForFileExtension(ext, expectedPath, testPath)
예제 #10
0
 def test_reloadFont(self):
     src = pathlib.Path(
         __file__).resolve().parent / "data" / "MutatorSans.ttf"
     assert src.exists()
     with tempfile.NamedTemporaryFile(suffix=".ttf") as ff:
         ff.write(src.read_bytes())
         firstModTime = os.stat(ff.name).st_mtime
         drawBot.newDrawing()
         drawBot.font(ff.name)
         self.assertEqual(ff.name, drawBot.fontFilePath())
         path = drawBot.BezierPath()
         path.text("E", font=ff.name, fontSize=1000)
         self.assertEqual((60.0, 0.0, 340.0, 700.0), path.bounds())
         ff.seek(0)
         ttf = TTFont(ff)
         ttf["glyf"]["E"].coordinates[0] = (400, 800)
         ff.seek(0)
         ttf.save(ff)
         secondModTime = os.stat(ff.name).st_mtime
         assert firstModTime != secondModTime, (firstModTime, secondModTime)
         drawBot.newDrawing()  # to clear the memoize cache in baseContext
         drawBot.font(ff.name)
         self.assertEqual(ff.name, drawBot.fontFilePath())
         path = drawBot.BezierPath()
         path.text("E", font=ff.name, fontSize=1000)
         self.assertEqual((60.0, 0.0, 400.0, 800.0), path.bounds())
예제 #11
0
 def test_newPage_empty_implicit_first_page(self):
     drawBot.newDrawing()
     drawBot.rect(100, 100, 200, 200)
     drawBot.newPage()
     self.assertEqual(drawBot.width(), 1000)
     self.assertEqual(drawBot.height(), 1000)
     self.assertEqual(drawBot.pageCount(), 2)
예제 #12
0
 def test_fontVariations(self):
     drawBot.newDrawing()
     var = drawBot.listFontVariations()
     self.assertEqual(var, {})
     drawBot.font("Skia")
     # get the default font variations
     var = drawBot.listFontVariations()
     expectedVar = {
         'wght': {
             'name': 'Weight',
             'minValue': 0.4799,
             'maxValue': 3.1999,
             'defaultValue': 1.0
         },
         'wdth': {
             'name': 'Width',
             'minValue': 0.6199,
             'maxValue': 1.2999,
             'defaultValue': 1.0
         }
     }
     self.assertEqual(var, expectedVar)
     # set a font variation
     var = drawBot.fontVariations(wght=5)
     expectedVarChanged = {'wght': 5, 'wdth': 1.0}
     self.assertEqual(var, expectedVarChanged)
     # clear all font variations settings
     var = drawBot.fontVariations(resetVariations=True)
     self.assertEqual(var, {'wght': 1.0, 'wdth': 1.0})
     drawBot.font("Helvetica")
     var = drawBot.listFontVariations()
     self.assertEqual(var, {})
     var = drawBot.fontVariations(wght=5)
     self.assertEqual(var, {"wght": 5})
예제 #13
0
def draw():
    for i in range(0, 100):
        drawBot.newDrawing()
        drawBot.newPage(1000, 1000)
        drawBot.radialGradient(
            (randint(1,500), randint(1,500)),                         # startPoint
            (randint(1,800), randint(1,800)),                         # endPoint
            [(randint(0,1), randint(0,1), randint(0,1)), (randint(0,1), randint(0,1), randint(0,1)), (randint(0,1), randint(0,1), randint(0,1))],  # colors
            [randint(0,1), randint(0,1), randint(0,1)],                         # locations
            randint(0,1),                                  # startRadius
            randint(0,800)                                # endRadius
        )
# draw a rectangle
        drawBot.rect(randint(0,100), randint(0,100), randint(0,1000), randint(0,1000))

# draw the path
        drawBot.drawPath()
        drawBot.blendMode("multiply")
# set a color
        drawBot.rect(randint(1,10), randint(1,10), randint(1,100), randint(1,100))

# draw oval x, y, width, height
        drawBot.oval(randint(1,500), randint(1,500), randint(1,500), randint(1,500))
        drawBot.oval(randint(1,500), randint(1,500), randint(1,500), randint(1,500))
        drawBot.cmykFill(randint(0,1), randint(0,1), randint(0,1), randint(0,1))
# draw a rectangle
        drawBot.rect(randint(1,10), randint(1,10), randint(1,1000), randint(1,1000))
# set an other color
        drawBot.cmykFill(randint(0,1), randint(0,1), randint(0,1), randint(0,1))
# overlap a second rectangle
        drawBot.rect(randint(1,500), randint(1,500), randint(1,600), randint(1,600))
        drawBot.saveImage(str(i) + '.png' )
        drawBot.endDrawing()
        print(str(i) + ' done.')
예제 #14
0
    def updateCanvas(self):
        db.newDrawing()
        db.newPage(1200, 740)
        self.draw()

        pdf = db.pdfImage()
        self.w.canvas.setPDFDocument(pdf)
예제 #15
0
 def test_fontVariations(self):
     drawBot.newDrawing()
     var = drawBot.listFontVariations()
     self.assertEqual(var, {})
     drawBot.font("Skia")
     # get the default font variations
     var = drawBot.listFontVariations()
     var['wght'] = _roundDictValues(var['wght'], 3)
     var['wdth'] = _roundDictValues(var['wdth'], 3)
     expectedVar = OrderedDict({
         'wght': {'name': 'Weight', 'minValue': 0.48, 'maxValue': 3.2, 'defaultValue': 1.0},
         'wdth': {'name': 'Width', 'minValue': 0.62, 'maxValue': 1.3, 'defaultValue': 1.0},
     })
     self.assertEqual(var, expectedVar)
     # set a font variation
     var = drawBot.fontVariations(wght=5)
     expectedVarChanged = {'wght': 5, 'wdth': 1.0}
     self.assertEqual(var, expectedVarChanged)
     # clear all font variations settings
     var = drawBot.fontVariations(resetVariations=True)
     self.assertEqual(var, {'wght': 1.0, 'wdth': 1.0})
     drawBot.font("Helvetica")
     var = drawBot.listFontVariations()
     self.assertEqual(var, {})
     var = drawBot.fontVariations(wght=5)
     self.assertEqual(var, {"wght": 5})
예제 #16
0
    def Composite(pens, rect, save_to, scale=2):
        db.newDrawing()
        rect = rect.scale(scale)
        db.newPage(rect.w, rect.h)

        def draw(pen, state, data):
            if state == 0:
                DrawBotPen(pen, rect).draw(scale=scale)
            elif state == -1:
                imgf = pen.data.get("imgf")
                if imgf:
                    im = db.ImageObject()
                    im.lockFocus()
                    db.size(rect.w+300, rect.h+300)
                    db.translate(150, 150)
                    db.scale(scale)
                    pen.data["im"] = im
            elif state == 1:
                imgf = pen.data.get("imgf")
                im = pen.data.get("im")
                if imgf and im:
                    im.unlockFocus()
                    imgf(im)
                    x, y = im.offset()
                    db.translate(-150, -150)
                    db.image(im, (x, y))
        
        if isinstance(pens, DATPen):
            pens = [pens]
        for dps in pens:
            dps.walk(draw)
        
        db.saveImage(str(save_to))
        db.endDrawing()
예제 #17
0
    def pageSetup(self):
        drawBot.newDrawing()
        drawBot.newPage("LetterLandscape")
        
        pageWidth = drawBot.width()
        pageHeight = drawBot.height()
        
        #drawBot.fill(0,0,0, 0.5)
        drawBot.stroke(0,0,0,.5)
        drawBot.strokeWidth(0.5)
        
        #this needs major clean up
        drawBot.line((margin, pageHeight-margin), (pageWidth-dpi, pageHeight-margin)) #xHeight line
        drawBot.line((margin, pageHeight-margin-self.xHeightTarget), (pageWidth-dpi, pageHeight-margin-self.xHeightTarget)) #baseline
        
        drawBot.line((margin, pageHeight-margin-(2.5*self.xHeightTarget)), (pageWidth-dpi, pageHeight-margin-(2.5*self.xHeightTarget))) #xHeight line
        drawBot.line((margin, pageHeight-margin-self.xHeightTarget-(2.5*self.xHeightTarget)), (pageWidth-dpi, pageHeight-margin-self.xHeightTarget-(2.5*self.xHeightTarget))) #baseline
        
        drawBot.line((margin, pageHeight-margin-(5*self.xHeightTarget)), (pageWidth-dpi, pageHeight-margin-(5*self.xHeightTarget))) #xHeight line
        drawBot.line((margin, pageHeight-margin-self.xHeightTarget-(5*self.xHeightTarget)), (pageWidth-dpi, pageHeight-margin-self.xHeightTarget-(5*self.xHeightTarget))) #baseline

        #drawBot.rect(margin, pageHeight-margin, pageWidth-dpi, -self.xHeightTarget)
        
        pdf = drawBot.pdfImage()
        # set the pdf data in the canvas
        self.w.canvas.setPDFDocument(pdf)
예제 #18
0
 def drawCurrentGlyph(self):
     db.newDrawing()
     db.translate(100, 100)
     db.scale(0.8)
     db.fill(None)
     db.stroke(0.2, 0.3, 1)
     db.rect(0, 0, 1000, 1000)
     db.stroke(None)
     db.translate(
         0, 120
     )  # Baseline at 120 from the bottom of the Ideographic Em Square
     db.fill(0, 1, 0, 0.3)
     db.stroke(0)
     db.lineJoin("round")
     dcSelection = set(self.w.deepComponentList.getSelection())
     aeSelection = set(self.w.atomicElementList.getSelection())
     if self._currentGlyphOutline is not None:
         drawOutline(self._currentGlyphOutline)
     if self._currentGlyphComponents:
         for dcIndex, (dcName, atomicElements) in enumerate(
             self._currentGlyphComponents
         ):
             for aeIndex, (aeName, atomicOutline) in enumerate(atomicElements):
                 if dcIndex in dcSelection:
                     if aeIndex in aeSelection:
                         db.fill(1, 0, 0, 0.3)
                     else:
                         db.fill(0, 0, 1, 0.3)
                 else:
                     db.fill(0, 0.3)
                 drawOutline(atomicOutline)
     db.endDrawing()
예제 #19
0
파일: testMisc.py 프로젝트: sahwar/drawbot
 def test_polygon_notEnoughPoints(self):
     drawBot.newDrawing()
     with self.assertRaises(TypeError):
         drawBot.polygon()
     with self.assertRaises(TypeError):
         drawBot.polygon((1, 2))
     drawBot.polygon((1, 2), (3, 4))
예제 #20
0
파일: testMisc.py 프로젝트: sahwar/drawbot
 def test_newPage_empty_implicit_first_page(self):
     drawBot.newDrawing()
     drawBot.rect(100, 100, 200, 200)
     drawBot.newPage()
     self.assertEqual(drawBot.width(), 1000)
     self.assertEqual(drawBot.height(), 1000)
     self.assertEqual(drawBot.pageCount(), 2)
예제 #21
0
 async def reload(self, trigger):
     try:
         load_drawbot = self.args.drawbot
         if load_drawbot:
             if not db:
                 raise Exception("Cannot run drawbot program without drawBot installed")
             else:
                 db.newDrawing()
         self.program = run_path(str(self.filepath))
         if load_drawbot:
             with tempfile.NamedTemporaryFile(suffix=".svg") as tf:
                 db.saveImage(tf.name)
                 self.preview.clear()
                 self.preview.send(f"<div class='drawbot-render'>{tf.read().decode('utf-8')}</div>", None)
             db.endDrawing()
         for k, v in self.program.items():
             if isinstance(v, coldtype.text.reader.Font):
                 await v.load()
                 if v.path not in self.watchee_paths():
                     self.watchees.append([Watchable.Font, v.path])
                 for ext in v.font.getExternalFiles():
                     if ext not in self.watchee_paths():
                         self.watchees.append([Watchable.Font, ext])
             elif isinstance(v, DefconFont):
                 p = Path(v.path).resolve()
                 if p not in self.watchee_paths():
                     self.watchees.append([Watchable.Font, p])
     except Exception as e:
         self.program = None
         self.show_error()
예제 #22
0
 def test_instructionStack(self):
     expected = [
         "reset None", "newPage 200 200", "save",
         "clipPath moveTo 5.0 5.0 lineTo 15.0 5.0 lineTo 15.0 15.0 lineTo 5.0 15.0 closePath",
         "restore", "image Image Object 10 10 0.5 None",
         "blendMode saturation", "transform 1 0 0 1 10 10",
         "drawPath moveTo 10.0 10.0 lineTo 110.0 10.0 lineTo 110.0 110.0 lineTo 10.0 110.0 closePath",
         "textBox foo bar 72.48291015625 84.0 55.0341796875 26.0 center",
         "frameDuration 10", "saveImage * {'myExtraAgrument': True}"
     ]
     with StdOutCollector() as output:
         import drawBot
         drawBot.newDrawing()
         drawBot.size(200, 200)
         drawBot.save()
         path = drawBot.BezierPath()
         path.rect(5, 5, 10, 10)
         drawBot.clipPath(path)
         drawBot.restore()
         im = drawBot.ImageObject()
         with im:
             drawBot.size(20, 20)
             drawBot.rect(5, 5, 10, 10)
         drawBot.image(im, (10, 10), alpha=.5)
         drawBot.blendMode("saturation")
         drawBot.translate(10, 10)
         drawBot.rect(10, 10, 100, 100)
         drawBot.text("foo bar", (100, 100), align="center")
         drawBot.frameDuration(10)
         drawBot.saveImage("*", myExtraAgrument=True)
         drawBot.endDrawing()
     self.assertEqual(output.lines(), expected)
예제 #23
0
def new_drawing(rect: Rect = Rect(1000, 1000), count=1, save_to=None):
    db.newDrawing()
    for idx in range(0, count):
        with new_page(rect) as r:
            yield idx, r
    if save_to:
        db.saveImage(str(save_to))
    db.endDrawing()
예제 #24
0
 def test_font_install(self):
     fontPath = os.path.join(testDataDir, "MutatorSans.ttf")
     drawBot.newDrawing()
     drawBot.newPage()
     postscriptName = drawBot.font(fontPath)
     self.assertEqual(postscriptName, "MutatorMathTest-LightCondensed")
     variations = drawBot.listFontVariations()
     self.assertEqual(variations, {'wdth': {'name': 'Width', 'minValue': 0.0, 'maxValue': 1000.0, 'defaultValue': 0.0}, 'wght': {'name': 'Weight', 'minValue': 0.0, 'maxValue': 1000.0, 'defaultValue': 0.0}})
예제 #25
0
 def __init__(self):
     drawBot.newDrawing()
     # A3, TODO: switch to A2.
     drawBot.newPage(1190, 842)
     self.stepIntoArena()
     self.juggle()
     path = '/Users/michiel/Desktop/circus.pdf'
     drawBot.saveImage(path)
예제 #26
0
 def test_polygon_unexpectedKeywordArgument(self):
     drawBot.newDrawing()
     drawBot.polygon((1, 2), (3, 4), close=True)
     drawBot.polygon((1, 2), (3, 4), close=False)
     with self.assertRaises(TypeError):
         drawBot.polygon((1, 2), (3, 4), closed=False)
     with self.assertRaises(TypeError):
         drawBot.polygon((1, 2), (3, 4), closed=False, foo=123)
예제 #27
0
 def test_newPage_empty_multiple(self):
     drawBot.newDrawing()
     drawBot.newPage()
     drawBot.newPage()
     drawBot.newPage()
     self.assertEqual(drawBot.width(), 1000)
     self.assertEqual(drawBot.height(), 1000)
     self.assertEqual(drawBot.pageCount(), 3)
예제 #28
0
파일: testMisc.py 프로젝트: sahwar/drawbot
 def test_polygon_unexpectedKeywordArgument(self):
     drawBot.newDrawing()
     drawBot.polygon((1, 2), (3, 4), close=True)
     drawBot.polygon((1, 2), (3, 4), close=False)
     with self.assertRaises(TypeError):
         drawBot.polygon((1, 2), (3, 4), closed=False)
     with self.assertRaises(TypeError):
         drawBot.polygon((1, 2), (3, 4), closed=False, foo=123)
예제 #29
0
파일: testMisc.py 프로젝트: sahwar/drawbot
 def test_newPage_empty_multiple(self):
     drawBot.newDrawing()
     drawBot.newPage()
     drawBot.newPage()
     drawBot.newPage()
     self.assertEqual(drawBot.width(), 1000)
     self.assertEqual(drawBot.height(), 1000)
     self.assertEqual(drawBot.pageCount(), 3)
예제 #30
0
    def draw(self, sender):

        db.newDrawing()
        db.newPage(300, 300)
        fill(random(), random(), random())
        db.rect(0, 0, 50, 50)

        self.pdf = db.pdfImage()
        self.w.drawView.setPDFDocument(self.pdf)
예제 #31
0
    def draw(self, saving=False, saveTo=None, fmt="pdf", layers=[], fill=None):
        savingToFont = isinstance(fmt, defcon.Font)
        if saving:
            db.newDrawing()
            self.saving = True
        else:
            self.saving = False

        db.newPage(*self.animation.dimensions)
        self.page = Rect.page()

        self.bps = {}
        for l in layers:
            self.bps[l] = RichBezier()

        with db.savedState():
            if fill and not saveTo:
                with db.savedState():
                    db.fill(*fill)
                    db.rect(*self.page)
            self.layers = layers
            self.animation.fn(self)
            self.layers = None
        if self.animation.burn:
            box = self.page.take(64,
                                 Edge.MinY).take(120,
                                                 Edge.MaxX).offset(-24, 24)
            db.fontSize(20)
            db.lineHeight(20)
            db.font("Menlo-Bold")
            db.fill(0, 0.8)
            db.rect(*box.inset(-14, -14).offset(0, 2))
            db.fill(1)
            db.textBox("{:07.2f}\n{:04d}\n{:%H:%M:%S}".format(
                self.time, self.i, datetime.datetime.now()),
                       box,
                       align="center")

        for k, bez in self.bps.items():
            with db.savedState():
                db.fill(*bez.fill)
                db.drawPath(bez.bp)

        if saving:
            if savingToFont:
                for k, bez in self.bps.items():
                    g = defcon.Glyph()
                    g.name = "frame_" + str(self.i)
                    g.unicode = self.i + 48  # to get to 0
                    g.width = self.animation.dimensions[0]
                    bez.bp.drawToPen(g.getPen())
                    fmt.insertGlyph(g)
            else:
                db.saveImage(f"{saveTo}/{self.i}.{fmt}")
            db.endDrawing()

        self.saving = False
예제 #32
0
 def test_linkURL_svg(self):
     expectedPath = os.path.join(testDataDir, "expected_svgLinkURL.svg")
     drawBot.newDrawing()
     drawBot.newPage(200, 200)
     drawBot.rect(10, 10, 20, 20)
     drawBot.linkURL("http://drawbot.com", (10, 10, 20, 20))
     with TempFile(suffix=".svg") as tmp:
         drawBot.saveImage(tmp.path)
         self.assertEqual(readData(tmp.path), readData(expectedPath), "Files %r and %s are not the same" % (tmp.path, expectedPath))
예제 #33
0
파일: testMisc.py 프로젝트: sahwar/drawbot
 def test_fontVariationNamedInstances(self):
     drawBot.newDrawing()
     namedInstances = drawBot.listNamedInstances()
     self.assertEqual(namedInstances, {})
     drawBot.font("Skia")
     namedInstances = drawBot.listNamedInstances()
     namedInstances = _roundInstanceLocations(namedInstances)
     expectedNamedInstances = {
         'Skia-Regular_Black': {
             'wght': 3.2,
             'wdth': 1.0
         },
         'Skia-Regular_Extended': {
             'wght': 1.0,
             'wdth': 1.3
         },
         'Skia-Regular_Condensed': {
             'wght': 1.0,
             'wdth': 0.61998
         },
         'Skia-Regular_Light': {
             'wght': 0.48,
             'wdth': 1.0
         },
         'Skia-Regular': {
             'wght': 1.0,
             'wdth': 1.0
         },
         'Skia-Regular_Black-Extended': {
             'wght': 3.2,
             'wdth': 1.3
         },
         'Skia-Regular_Light-Extended': {
             'wght': 0.48,
             'wdth': 1.3
         },
         'Skia-Regular_Black-Condensed': {
             'wght': 3.0,
             'wdth': 0.7
         },
         'Skia-Regular_Light-Condensed': {
             'wght': 0.48,
             'wdth': 0.7
         },
         'Skia-Regular_Bold': {
             'wght': 1.95,
             'wdth': 1.0
         }
     }
     expectedNamedInstances = _roundInstanceLocations(
         expectedNamedInstances)
     self.assertEqual(namedInstances, expectedNamedInstances)
     drawBot.font("Helvetica")
     namedInstances = drawBot.listNamedInstances("Skia")
     namedInstances = _roundInstanceLocations(namedInstances)
     self.assertEqual(namedInstances, expectedNamedInstances)
예제 #34
0
 def makeTestAnimation(self, numFrames=25, pageWidth=500, pageHeight=500):
     randomSeed(0)
     drawBot.newDrawing()
     for i in range(numFrames):
         drawBot.newPage(pageWidth, pageHeight)
         drawBot.frameDuration(1/25)
         drawBot.fill(1)
         drawBot.rect(0, 0, pageWidth, pageHeight)
         drawBot.fill(0)
         drawBot.rect(random.randint(0, 100), random.randint(0, 100), 400, 400)
예제 #35
0
 def test_export_svg_fallbackFont(self):
     expectedPath = os.path.join(testDataDir, "expected_svgSaveFallback.svg")
     drawBot.newDrawing()
     drawBot.newPage(100, 100)
     drawBot.fallbackFont("Courier")
     drawBot.font("Times")
     drawBot.text("a", (10, 10))
     with TempFile(suffix=".svg") as tmp:
         drawBot.saveImage(tmp.path)
         self.assertEqual(readData(tmp.path), readData(expectedPath), "Files %r and %s are not the same" % (tmp.path, expectedPath))
예제 #36
0
 def test_formattedStringURL_svg(self):
     expectedPath = os.path.join(testDataDir, "expected_formattedStringURL.svg")
     drawBot.newDrawing()
     drawBot.newPage(200, 200)
     drawBot.underline("single")
     drawBot.url("http://drawbot.com")
     drawBot.text("foo", (10, 10))
     with TempFile(suffix=".svg") as tmp:
         drawBot.saveImage(tmp.path)
         self.assertEqual(readData(tmp.path), readData(expectedPath), "Files %r and %s are not the same" % (tmp.path, expectedPath))
예제 #37
0
    def build(self):
        """Build the document by looping trough the pages, an then recursively
        tell every page to build itself (and its contained elements).
        """
        # Clear all previous drawing in the DrawBot canvas.
        drawBot.newDrawing()

        # Tell each page to build itself in DrawBot, including their child elements.
        for page in self.pages:
            page.build(self) # Passing self as document, in case the page needs more info.
        self.hasBuilt = True # Flag that we did this, in case called separate from self.export.
예제 #38
0
 def test_openTypeFeatures(self):
     drawBot.newDrawing()
     fea = drawBot.listOpenTypeFeatures()
     self.assertEqual(fea, {'liga': True})
     drawBot.font("Helvetica")
     fea = drawBot.listOpenTypeFeatures()
     self.assertEqual(fea, {'liga': True, 'tnum': True, 'pnum': False})
     fea = drawBot.listOpenTypeFeatures("HoeflerText-Regular")
     self.assertEqual(fea, {'liga': True, 'dlig': False, 'tnum': True, 'pnum': False, 'titl': True, 'onum': True, 'lnum': False})
     fea = drawBot.openTypeFeatures(liga=False)
     self.assertEqual(fea, {'liga': False, 'tnum': True, 'pnum': False})
     drawBot.font("LucidaGrande")
     fea = drawBot.openTypeFeatures(resetFeatures=True)
     self.assertEqual(fea, {'liga': True})
def GoldFactory(glyph, font=None, offset=10):
    glyph = RGlyph(glyph)
    box = glyph.bounds if version >= "3.0" else glyph.box
    if box is None:
        return None
    margin = offset * 2
    minx, miny, maxx, maxy = box
    w = maxx - minx + margin * 2
    h = maxy - miny + margin * 2

    drawBot.newDrawing()
    drawBot.newPage(w, h)
    drawBot.translate(-minx + margin, -miny + margin)

    if font is None:
        font = glyph.font if version >= "3.0" else glyph.getParent()

    glyphSet = font

    g = glyph.copy()

    for component in reversed(g.components):
        if version >= "3.0":
            decomposePen = DecomposePointPen(glyphSet, g.getPointPen())
        else:
            decomposePen = DecomposePointPen(glyphSet, g.getPointPen(), [1, 0, 0, 1, 0, 0])
        component.drawPoints(decomposePen)
        g.removeComponent(component)

    g.removeOverlap()

    minx, miny, maxx, maxy = g.bounds if version >= "3.0" else g.box

    setGoldGradient(minx, miny, maxx, maxy)
    drawBot.drawGlyph(g)

    pen = OutlinePen(glyphSet, offset=offset)
    g.draw(pen)
    pen.drawSettings(drawInner=True, drawOuter=True)

    dest = RGlyph()
    pen.drawPoints(dest.getPointPen())

    setGoldGradient(minx, miny, maxx, maxy, 4)
    drawBot.drawGlyph(dest)

    pdf = drawBot.pdfImage()
    page = pdf.pageAtIndex_(0)
    image = NSImage.alloc().initWithData_(page.dataRepresentation())
    return image, (minx-margin, miny-margin)
예제 #40
0
 def test(self):
     # get the paths
     testPath = os.path.join(tempTestDataDir, "%s.%s" % (scriptName, ext))
     expectedPath = os.path.join(testDataDir, "expected_%s.%s" % (scriptName, ext))
     expectedOutputPath = os.path.join(testDataDir, "expected_%s.txt" % scriptName)
     expectedOutput = readExpectedOutput(expectedOutputPath)
     # get drawBot
     import drawBot
     # start a new drawing
     drawBot.newDrawing()
     # execute the script in place
     # temporarily ignore deprecation warnings (there are some from PyObjC :( )
     with warnings.catch_warnings():
         if ignoreDeprecationWarnings:
             warnings.simplefilter("ignore", DeprecationWarning)
         output = self.executeScriptPath(path)
     self.assertEqual(cleanupTraceback(output), cleanupTraceback(expectedOutput))
     # save the image
     drawBot.saveImage(testPath)
     # tell drawBot drawing is done
     drawBot.endDrawing()
     self.assertForFileExtension(ext, expectedPath, testPath)
예제 #41
0
 def test_instructionStack(self):
     expected = [
         "reset None",
         "newPage 200 200",
         "save",
         "clipPath moveTo 5.0 5.0 lineTo 15.0 5.0 lineTo 15.0 15.0 lineTo 5.0 15.0 closePath",
         "restore",
         "image Image Object 10 10 0.5 None",
         "blendMode saturation",
         "transform 1 0 0 1 10 10",
         "drawPath moveTo 10.0 10.0 lineTo 110.0 10.0 lineTo 110.0 110.0 lineTo 10.0 110.0 closePath",
         "textBox foo bar 82.48291015625 84.0 35.0341796875 26.0 center",
         "frameDuration 10",
         "saveImage * {'myExtraAgrument': True}"
     ]
     with StdOutCollector() as output:
         import drawBot
         drawBot.newDrawing()
         drawBot.size(200, 200)
         drawBot.save()
         path = drawBot.BezierPath()
         path.rect(5, 5, 10, 10)
         drawBot.clipPath(path)
         drawBot.restore()
         im = drawBot.ImageObject()
         with im:
             drawBot.size(20, 20)
             drawBot.rect(5, 5, 10, 10)
         drawBot.image(im, (10, 10), alpha=.5)
         drawBot.blendMode("saturation")
         drawBot.translate(10, 10)
         drawBot.rect(10, 10, 100, 100)
         drawBot.text("foo bar", (100, 100), align="center")
         drawBot.frameDuration(10)
         drawBot.saveImage("*", myExtraAgrument=True)
         drawBot.endDrawing()
     self.assertEqual(output.lines(), expected)
예제 #42
0
    def test(self):
        import __future__
        from drawBot.drawBotDrawingTools import _drawBotDrawingTool

        compileFlags = __future__.CO_FUTURE_DIVISION
        code = compile(source, "<%s>" % exampleName, "exec", flags=compileFlags, dont_inherit=True)

        namespace = {}
        _drawBotDrawingTool._addToNamespace(namespace)
        def mockSaveImage(path, **options):
            fileName = "example_mockSaveImage_" + os.path.basename(path)
            path = os.path.join(tempTestDataDir, fileName)
            drawBot.saveImage(path, **options)
        namespace["saveImage"] = mockSaveImage
        namespace["image"] = mockImage
        namespace["imageSize"] = mockImageSize
        namespace["imagePixelColor"] = mockImagePixelColor
        namespace["Variable"] = mockVariable
        namespace["printImage"] = mockPrintImage
        namespace["installFont"] = mockInstallFont
        namespace["uninstallFont"] = mockUninstallFont
        namespace["randint"] = mockRandInt

        randomSeed(0)
        drawBot.newDrawing()
        with StdOutCollector(captureStdErr=True):
            exec(code, namespace)
        fileName = "example_%s.png" % exampleName
        imagePath = os.path.join(tempTestDataDir, fileName)
        expectedImagePath = os.path.join(testDataDir, fileName)
        if doSaveImage:
            drawBot.saveImage(imagePath)
            if allowFuzzyImageComparison:
                self.assertImagesSimilar(imagePath, expectedImagePath)
            else:
                self.assertFilesEqual(imagePath, expectedImagePath)
예제 #43
0
import drawBot
drawBot.newDrawing()
drawBot.size(200, 100)
p = drawBot.BezierPath()
p.oval(5, 5, 70, 70)
p.rect(25, 25, 70, 70)
drawBot.fill(0, 0.3)
drawBot.stroke(0)
drawBot.drawPath(p)
p.removeOverlap()
drawBot.translate(100, 0)
drawBot.drawPath(p)
예제 #44
0
 def test_openTypeFeatures_saveRestore(self):
     drawBot.newDrawing()
     drawBot.font("AppleBraille")
     drawBot.save()
     drawBot.restore()