def draw(txt="a", variations={}, caption=""): db.newPage(w * scale, h * scale) db.scale(scale) db.fill(*BACKCOL) db.rect(0, 0, w, h) txt = db.FormattedString(txt, font="Handjet-Regular", fontSize=500, fontVariations=variations) db.fill(*TEXTCOL) db.stroke(None) path = db.BezierPath() path.text(txt, (w / 2, 95), align="center") db.drawPath(path) txt = db.FormattedString(caption, font="AdapterMonoPE-Regular", fontSize=11, fill=TEXTCOL) db.text(txt, (w / 2, 40), align="center")
def _get_fs(self): """Property that creates a new DrawBot.FormattedString from the current set of runs, if the cached value self._fs does not already exist. Otherwise just answer the cached value. >>> bs = BabelString('Hello world', dict(font='Georgia')) >>> bs.fs, isinstance(bs.fs, drawBot.FormattedString().__class__) (Hello world, True) """ if self._fs is None: self._fs = fs = drawBot.FormattedString() for run in self.runs: fsStyle = self._getFSStyle(run.style) fs.append(drawBot.FormattedString(run.s, **fsStyle)) return self._fs
def export(self, path): """Draw a page and export the document into the _export folder. Note that in this version, we still generate the document page just before it is exported. Not Page instances are stored in the Document yet. >>> doc = Document() >>> doc.export('_export/Document-export.jpg') # Exporting the JPG """ # Make sure that the _export folder exists, as it does not standard # dowload from Github, nor it is committed to Github. if path.startswith(EXPORT_DIR) and not os.path.exists(EXPORT_DIR): os.mkdir(EXPORT_DIR) # Now let DrawBot do its work, creating the page canvas, filling it # black, add the title text and then saving it. drawBot.newPage(self.w, self.h) # For now to have something visible, draw a gray rectangle filling the page. drawBot.fill(0.2) # Set fill color at 20% dark gray. drawBot.rect(0, 0, self.w, self.h) # Draw the rectangle for the entire page. # Create a Formatted String for white text with the specified font/fontSize. fs = drawBot.FormattedString('My specimen', font='Georgia', fontSize=80, fill=1) # Draw the FormattedString on this fixed position: x from left and y from top. drawBot.text(fs, (50, self.h - 100)) # Save the drawn DrawBot page into the _export folder, using `path` as file name. # File in the _export folder are ignored by Git, so they don't upload. drawBot.saveImage(path)
def draw(gn="a", variations={}, caption=""): db.newPage(w * scale, h * scale) db.scale(scale) db.fill(*BACKCOL) db.rect(0, 0, w, h) fs = db.FormattedString() fs.font("Handjet-Regular") fs.fontSize(200) fs.appendGlyph(gn) db.fill(*TEXTCOL) db.stroke(None) path = db.BezierPath() path.text(fs, (w / 2, 145), align="center") db.drawPath(path) fs = db.FormattedString(caption, font="AdapterMonoPE-Regular", fontSize=10, fill=TEXTCOL) db.text(fs, (w / 2, 40), align="center")
def test_formattedString_issue337_part3(self): # Verifying we get the correct line height on an empty string expected = [ 'reset None', 'newPage 1000 1000', 'textBox A 0 -34.0 26.8994140625 104.0 left', 'textBox B 0 -46.0 25.751953125 104.0 left', 'textBox C 0 -58.0 26.9189453125 104.0 left', 'textBox A 10 -34.0 26.8994140625 104.0 left', 'textBox 10 48.0 20.0 104.0 left', 'textBox C 10 -58.0 26.9189453125 104.0 left', 'saveImage * {}' ] with StdOutCollector() as output: drawBot.newDrawing() fs = drawBot.FormattedString("A\nB\nC\n") drawBot.text(fs, (0, 60)) fs = drawBot.FormattedString("A\n\nC\n") drawBot.text(fs, (10, 60)) drawBot.saveImage("*") drawBot.endDrawing() self.assertEqual(output.lines(), expected)
def drawCell(glyphName, cellWidth, cellHeight, cellLegendSize): # Cell outline db.fill(None) db.stroke(0) db.strokeWidth(0.25) db.rect(0, 0, cellWidth, cellHeight) charArea = cellWidth / 3.5 fontSize = charArea * 0.7 charStartingOffset = (cellWidth * 0.5) - (charArea * 1.5) # Glyph sample for iH, aH in enumerate(angles): for iV, aV in enumerate(reversed(angles)): locStr = "%s %s" % (aH, aV) f = instances[locStr] if glyphName in f: g = f[glyphName] with db.savedState(): db.translate(charStartingOffset, charStartingOffset ) # Center the nine glyphs in the cell db.translate( iH * charArea, iV * charArea) # Move to the current glyph in the cell db.translate(charArea * 0.5, 0) # Offset to center glyph in cell db.translate(0, cellLegendSize * 3) # Leave room for the legend # Draw db.fill(0) db.stroke(None) db.scale(fontSize / 1000) drawGlyph(g) # Legend db.fill(None) db.stroke(0) db.strokeWidth(0.25) db.lineCap("round") db.line((cellLegendSize, cellLegendSize * 3), (cellWidth - cellLegendSize, cellLegendSize * 3)) unicodeValueStr = "" if g.unicode: unicodeValueStr = hex(g.unicode) legendText = "%s\n%s" % (g.name, unicodeValueStr) fs = db.FormattedString(legendText, font="Tilt Neon", fontSize=cellLegendSize, tracking=1, lineHeight=cellLegendSize) db.text(fs, (cellLegendSize, cellLegendSize * 1.7))
def startNewPage(pageWidth, pageHeight, margin, header): db.newPage(pageWidth, pageHeight) # Draw the header with db.savedState(): fs = db.FormattedString("%s Glyph Overview\n" % HEADER_STYLENAME, font="Tilt Neon", fontSize=15) fs.append("by Andy Clymer\n%s" % HEADER_URL, font="Tilt Neon", fontSize=8) db.translate(margin, db.height() - header - margin) db.textBox(fs, (0, 0, db.width() - (margin * 2), header))
def test_textBoxCharacterBounds(self): drawBot.newDrawing() t = drawBot.FormattedString() t += "hello " * 2 t.fontSize(30) t += "foo " * 2 t.font("Times") t += "bar " * 2 t.fontSize(40) t += "world " * 2 bounds = drawBot.textBoxCharacterBounds(t, (10, 10, 300, 300)) self.assertEqual([i.bounds for i in bounds], [(10.0, 278.890625, 53.73046875, 11.77734375), (63.73046875, 274.671875, 114.755859375, 35.33203125), (178.486328125, 273.5, 91.611328125, 30.0), (10.0, 225.0, 206.640625, 40.0)]) self.assertEqual([i.baselineOffset for i in bounds], [2.109375, 6.328125, 7.5, 10.0]) self.assertEqual([str(i.formattedSubString) for i in bounds], ['hello hello ', 'foo foo ', 'bar bar ', 'world world '])
def draw(txt="a", variations={}, caption=""): db.newPage(w * scale, h * scale) db.scale(scale) db.fill(*BACKCOL) db.stroke(None) db.rect(0, 0, w, h) fs = db.FormattedString(txt, font="Handjet-Regular", fontSize=4600, fontVariations=variations) path = db.BezierPath() path.text(fs, (w / 2, 1.58 * h), align="center") path_optim = path.copy() # remove overlaps when drawing the fill # but use the original contour when drawing the nodes path_optim.removeOverlap() path_optim.optimizePath() # draw the fill db.fill(*TEXTCOL) db.drawPath(path_optim) # draw nodes if path.contours: # drawing just the first contour is enough for s in path.contours[0]: for x, y in s: if (x, y) in path.onCurvePoints: db.fill(*NODECOL) db.stroke(*TEXTCOL) db.strokeWidth(1) db.oval(x - 4, y - 4, 8, 8) # draw caption fs = db.FormattedString(caption, font="AdapterMonoPE-Regular", fontSize=10, fill=TEXTCOL) if caption: db.text(fs, (w / 2, 40), align="center")
def test_textBoxBaselines(self): drawBot.newDrawing() baselines = drawBot.textBoxBaselines("hello foo bar world " * 10, (10, 10, 300, 300)) self.assertEqual(baselines, [(10.0, 300.0), (10.0, 288.0), (10.0, 276.0), (10.0, 264.0)]) t = drawBot.FormattedString() t += "hello " * 2 t.fontSize(30) t += "foo " * 2 t.font("Times") t += "bar " * 2 t.fontSize(40) t += "world " * 2 baselines = drawBot.textBoxBaselines(t, (10, 10, 300, 300)) self.assertEqual(baselines, [(10.0, 281.0), (10.0, 235.0)])
def feelingSlide(canvasWidth, canvasHeight, polarity): db.newPage(canvasWidth, canvasHeight) background_fill = polarityBackground(polarity) db.fill(*background_fill) db.frameDuration(4) db.rect(0, 0, canvasWidth, canvasHeight) background_images = os.listdir('background_images/') background_image_path = 'background_images/' + background_images[(int)( len(background_images) * random.random())] # https://forum.drawbot.com/topic/180/how-do-i-size-an-image-with-the-imageobject-or-without/4 srcWidth, srcHeight = db.imageSize(background_image_path) dstWidth, dstHeight = canvasWidth - 50, canvasHeight - 50 factorWidth = dstWidth / srcWidth factorHeight = dstHeight / srcHeight with db.savedState(): db.translate(25, 25) with db.savedState(): db.scale(factorWidth, factorHeight) db.image(background_image_path, (0, 0)) dril_feels_text = db.FormattedString() dril_feels_text.append("@dril feels", font="Calibri-Bold", fontSize=150, fill=1, align='center', stroke=background_fill, strokeWidth=0.5) db.shadow((0, 0), 50, background_fill) db.text(dril_feels_text, (canvasWidth / 2, canvasHeight - 300)) if polarity < -0.1: drils_feeling = "angry" db.font("LucidaBlackletter", 250) elif polarity < 0.25: drils_feeling = "neutral" db.font("Helvetica", 180) else: drils_feeling = "happy" db.font("Cortado", 250) db.fill(1) db.shadow((0, 0), 50, background_fill) db.text(drils_feeling, (canvasWidth / 2, 250), align='center')
def build(self, doc): """Recursively make the pages to draw themselves in DrawBot. The build is “broadcast” to all the elements on the page. """ drawBot.newPage(self.w, self.h) # Create a new DrawBot page. for element in self.elements: # Passing on doc and this page in case an element needs more info. element.build(doc, self) # Now let DrawBot do its work, creating the page and saving it. # For now to have something visible. # Fill the page with a random dark color (< 50% for (r, g, b)) drawBot.fill(random() * 0.5, random() * 0.5, random() * 0.5) drawBot.rect(0, 0, self.w, self.h) fs = drawBot.FormattedString('My specimen\nPage %d' % self.pn, font='Georgia', fontSize=80, fill=1) drawBot.text(fs, (50, self.h - 100))
def test_export_SVG_mixin(self): expectedPath = os.path.join(testDataDir, "expected_svgMixin.svg") drawBot.newDrawing() drawBot.newPage(100, 100) path = drawBot.BezierPath() path.svgID = "hello" path.svgClass = "foo bar" path.svgLink = "drawbot.com" path.rect(0, 0, 20, 20) drawBot.drawPath(path) txt = drawBot.FormattedString() txt += "world" txt.svgID = "hello" txt.svgClass = "foo bar" txt.svgLink = "drawbot.com" drawBot.text(txt, (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))
def drawText(sf, ma, md, texts): if len(texts) != 0: try: # this depends on Glyphs versions? columnX = texts[0].parent().width + 20 / sf except: columnX = texts[0].parent.width + 20 / sf d.stroke(None) d.fill(1, 0, 0, 1) d.font(".SF Compact Text", 10 / sf) columnText = "" for i, a in enumerate(texts): x, y, wid = a.x, a.y, a.width d.text(str(i + 1), (x, y)) columnText += "%s\t%s\n\n" % (i + 1, a.text) t = d.FormattedString() t.fill(1, 0, 0, 1) t.font(".SF Compact Text", 10 / sf) t.firstLineIndent(-10 / sf) t.tabs((10, "left")) t += columnText columnW = min(250 / sf, (d.width() - margin) / sf - a.layer.bounds[1][0]) d.textBox(t, (columnX, md, columnW, ma - md))
def export(self, path): """Draw a page and export the document into the _export folder. Note that in this version, we still generate the document page at just before it is exported. Not Page instances are stored in the Document yet. """ # Make sure that the _export folder exists, as it does not standard # dowload from Github, nor it is committed to Github. if path.startswith(EXPORT_DIR) and not os.path.exists(EXPORT_DIR): os.mkdir(EXPORT_DIR) # Now let DrawBot do its work, creating the page and saving it. drawBot.newPage(self.w, self.h) # For now to have something visible, draw a gray rectangle filling the page. drawBot.fill(0.2) # Set fill color at 20% black. drawBot.rect(0, 0, self.w, self.h) # Draw the rectangle. # Create a Formatted String in white with specified font/fontSize. fs = drawBot.FormattedString('My specimen', font='Georgia', fontSize=80, fill=1) # Draw the FormattedString on this fixed position. drawBot.text(fs, (50, self.h - 100)) # Save the drawn DrawBot page into the _export folder, using `path` as file name. drawBot.saveImage(path)
except: pass else: style_name = " " return style_name for i, word in enumerate(args.words): key = lower_file_name(word) fontSize = 1000 font = fonts[i%len(fonts)] sub_folder = font.parent.stem bez = db.BezierPath() db.fontSize(fontSize) db.font(font) s = db.FormattedString(word, fontSize=fontSize, font=font) content_width, content_height = db.textSize(word) space = db.textSize(" ")[0] bez.text(s, (0, 0)) yShift = abs(db.fontDescender())+50 bez.translate(0, yShift) bez_left, bez_bottom, bez_right, bez_top = bez.bounds() canvas_width = content_width canvas_height = db.fontAscender() + abs(db.fontDescender()) + 100 cutoff_left = abs(bez_left) if bez_left < 0 else 0 cutoff_right = bez_right - content_width if bez_right > content_width else 0
# https://github.com/typemytype/drawbot/issues/427 import drawBot drawBot.size(200, 200) fs = drawBot.FormattedString() fs.font("Lucida Grande") fs.fontSize(50) fs.appendGlyph("H") fs.appendGlyph("i") drawBot.text(fs, (30, 110)) fs = drawBot.FormattedString() fs.font("Lucida Grande") fs.fontSize(50) fs.tracking(10) fs.appendGlyph("H") fs.appendGlyph("i") drawBot.text(fs, (30, 50))
def FormattedString(self, txt, **kwargs): if 'fill' in kwargs and isinstance(kwargs['fill'], Color): kwargs['fill'] = kwargs['fill'].rgb if 'stroke' in kwargs and isinstance(kwargs['stroke'], Color): kwargs['stroke'] = kwargs['stroke'].rgb return drawBot.FormattedString(txt, **kwargs)
def makeInstance(self, axes, gname, glyph): nbAxes = maxNbAxes = len(axes) # steps = [1, 2] # maxNbAxes = max(steps) # for nbAxes in steps: speeds = [1 for i in range(nbAxes)] # LCM = self.ilcm(speeds) LCM = 60 # print(LCM) # while ((LCM < 600 or LCM > 1200) or self.checkEqual(speeds)): # speeds = [int(10/nbAxes + random.random()*60/nbAxes) for i in range(nbAxes)] # LCM = self.ilcm(speeds) # print(speeds, LCM, (LCM < 600 or LCM > 1200)) alpha = 2 * math.pi / maxNbAxes ld = [{'Axis': l, 'PreviewValue': 0} for l in axes] # glyph.preview.computeDeepComponentsPreview(ld) origineGlyph = RGlyph() for atomicInstance in glyph.preview(): atomicInstance = atomicInstance.glyph atomicInstance.draw(origineGlyph.getPen()) # origineGlyph = glyph.preview.variationPreview.copy() origineGlyph.name = "interpo" db.newDrawing() for k in range(nbAxes): start = time.time() ld = [{ 'Axis': l, 'PreviewValue': j == k } for j, l in enumerate(axes)] # glyph.preview.computeDeepComponentsPreview(ld) for g in range(LCM): H = 700 W = 700 db.newPage(W * 2.5, H) db.frameDuration(1 / 30) db.fill(1) db.rect(0, 0, W * 2.5, H) r = W / 3 ainc = 0 lines = [] rands = [] values = [] for i in range(nbAxes): path = db.BezierPath() path.moveTo((H / 2, W / 2)) line = (r * math.sin(ainc), r * math.cos(ainc)) path.lineTo((H / 2 + line[0], W / 2 + line[1])) dx = line[0] * .05 dy = line[1] * .05 path.moveTo((H / 2 + line[0] - dy, W / 2 + line[1] + dx)) path.lineTo((H / 2 + line[0] + dy, W / 2 + line[1] - dx)) db.stroke(.2) db.strokeWidth(1.5) db.fill(None) db.drawPath(path) ainc += alpha lines.append((line, axes[i]["sourceName"])) # v = getValueForAxeAtFrame(i, g, nbAxes, LCM, speeds[i]) # values.append(v) if i == k: rands.append([ 1000 * abs( math.sin(math.pi * (speeds[i] * c / LCM + speeds[i]))) for c in range(LCM) ]) else: rands.append([0 for c in range(LCM)]) db.fill(1) db.oval(H / 2 - H * .01, W / 2 - W * .01, H * .02, W * .02) patharea = db.BezierPath() patharea.moveTo((H / 2, W / 2)) patharea.lineTo((H / 2 + lines[0][0][0] * rands[0][g] / 1000, W / 2 + lines[0][0][1] * rands[0][g] / 1000)) db.fill(0, 0, 0, .1) db.stroke(None) for c, (line, lineName) in enumerate(lines): patharea.lineTo((H / 2 + line[0] * rands[c][g] / 1000, W / 2 + line[1] * rands[c][g] / 1000)) patharea.lineTo((H / 2 + lines[0][0][0] * rands[0][g] / 1000, W / 2 + lines[0][0][1] * rands[0][g] / 1000)) patharea.lineTo((H / 2, W / 2)) db.drawPath(patharea) for c, (line, lineName) in enumerate(lines): db.fill(0) #1-rands[c] db.stroke(.2) db.strokeWidth(1) db.oval(H / 2 + line[0] * rands[c][g] / 1000 - 4.5, W / 2 + line[1] * rands[c][g] / 1000 - 4.5, 9, 9) db.fill(.2) ftxt = db.FormattedString(txt=lineName, font="GrtskZetta-Light", fontSize=14, align="center") db.textBox(ftxt, (H / 2 + line[0] * 1.3 - 30, W / 2 + line[1] * 1.3 - 10, 60, 20)) ######### db.save() # ld = [] # for j, l in enumerate(axes): # ld.append({'Axis': l, 'PreviewValue':rands[j][g]/1000}) # # d = {l:rands[j][g]/1000 for (j, l) in enumerate(axes)} # # glyph = interpolation(NewFont().newGlyph('temp'), ufo[gname], layersInfo = d) # # glyph = self.RCJKI.currentFont.get(gname) # glyph.preview.computeDeepComponentsPreview(ld) ######### # print(glyph) db.translate(W * 1.3, H * .15) db.scale(.7 * H / 1000) db.stroke(.5) db.fill(None) db.rect(0, 0, 1000, 1000) db.fill(0) db.stroke(None) db.save() db.translate(0, 120) ratioX = ratioY = (rands[k][g]) / 1000 resultGlyph = RGlyph() locations = {} for e in ld: locations[e["Axis"]["sourceName"]] = e["PreviewValue"] for c in glyph.preview(locations): c = c.glyph c.draw(resultGlyph.getPen()) interpoGlyph = interpolation.interpol_glyph_glyph_ratioX_ratioY_scaleX_scaleY( origineGlyph, resultGlyph, ratioX, ratioY, 1, 1, NewFont(showUI=False)) db.drawGlyph(interpoGlyph) # for aes in glyph.preview: # # axis2layerName = {axisName:layerName for axisName, layerName in self.RCJKI.currentFont[aes['name']].lib['robocjk.atomicElement.glyphVariations'].items()} # # lInfos = {axis2layerName[axisName]:v for axisName, v in aes['coord'].items()} # # print(ae['coord']) # for ae in aes.values(): # glyph = ae[0] # print(glyph) # db.save() # self._drawGlyph(glyph) # db.restore() db.restore() db.restore() caption = db.FormattedString(txt='%s-axis' % (nbAxes), font="GrtskMega-Medium", fontSize=14, align="left") db.textBox(caption, (10, 10, W - 20, 20)) stop = time.time() print(stop - start, "seconde for axis") pdfData = db.pdfImage()
from datetime import datetime import drawBot import os drawBot.newDrawing() fontDir = 'otf' for fontFileName in os.listdir(fontDir): if not fontFileName.endswith(".otf"): continue fontURL = os.path.join(fontDir, fontFileName) txt = drawBot.FormattedString() txt.font(fontURL) # Glyphset txt.fontSize(240) txt.lineHeight(220) txt.appendGlyph(*txt.listFontGlyphNames()) # Words txt.fontSize(24) txt.lineHeight(28) txt += "\n" * 2 txt += "encaissasses seize cas cane ni nies naine cessasses cessas sens an aise assainissez zen scia sains cannisses sana sic sis seize cannisse assainissez encaissasses encaissiez encaissassiez encens essais aines encaissez encaissassiez casasses scies cas cas incises zinc an ans incisasse sens sise sis canna canisse saines aines cessa assainisses naissais inca encan cannes cassas anis ces encaisse nazies ac assassiniez science aisance sic sciences canne zinc naisses canines cas naine cas encaissiez se saisie assainissez cc encaissais sans incisassiez sain saisissez cessassiez se sic ceci anse ac aines ananas saisissiez nia encaissez aise zizanies saisies nain ci ai cannas nez saisi nias ananas naine ancien cc naissance"
def test_formattedString_issue337_part2(self): # https://github.com/typemytype/drawbot/issues/337 drawBot.newDrawing() fs = drawBot.FormattedString("A\n\n") drawBot.text(fs, (0, 0))
def _drawReport(self, referenceFont, someFonts, glyphNames, reportPath, caption): assert isinstance(reportPath, str) or isinstance( reportPath, unicode), 'this should be a string or unicode' assert isinstance(someFonts, list), 'this should be a list of RFont' prog = ProgressWindow(text='{}: drawing glyphs...'.format(caption), tickCount=len(glyphNames)) try: db.newDrawing() twoLinesFontStyles = [ ff.info.styleName.replace(' ', '\n') for ff in someFonts ] quota = self._initPage(twoLinesFontStyles) for indexName, eachGlyphName in enumerate(glyphNames): db.save() db.translate(PDF_MARGIN, quota) # set name for eachSetName, eachGroup in SMART_SETS: if eachGlyphName in eachGroup: setName = eachSetName[3:].replace('.txt', '').replace( '_', ' ') break else: setName = '' db.text(setName, (COLS['set name'], 0)) # line number db.fill(*BLACK) db.text('{:0>4d}'.format(indexName), (COLS['line'], 0)) # unicode hex if eachGlyphName in referenceFont and referenceFont[ eachGlyphName].unicode: uniIntValue = referenceFont[eachGlyphName].unicode elif eachGlyphName in someFonts[0] and someFonts[0][ eachGlyphName].unicode: uniIntValue = someFonts[0][eachGlyphName].unicode else: uniIntValue = None if uniIntValue: uniHexValue = 'U+{:04X}'.format(uniIntValue) db.fill(*BLACK) db.text(uniHexValue, (COLS['unicode'], 0)) # os char if uniIntValue: txt = db.FormattedString() txt.fontSize(BODY_SIZE_GLYPH) txt.fill(*GRAY) txt += 'H' txt.fill(*BLACK) txt += unichr(uniIntValue) txt.fill(*GRAY) txt += 'p' db.text(txt, (COLS['char'], 0)) # glyphname db.fontSize(BODY_SIZE_TEXT) db.text(eachGlyphName, (COLS['glyph name'], 0)) # glyphs db.translate(COLS['template'], 0) for eachFont in [referenceFont] + someFonts: if eachGlyphName in eachFont: eachGlyph = eachFont[eachGlyphName] lftRefGL = eachFont['H'] rgtRefGL = eachFont['p'] db.save() db.scale(BODY_SIZE_GLYPH / eachFont.info.unitsPerEm) db.fill(*GRAY) db.drawGlyph(lftRefGL) db.translate(lftRefGL.width, 0) db.fill(*BLACK) db.drawGlyph(eachGlyph) db.translate(eachGlyph.width, 0) db.fill(*GRAY) db.drawGlyph(rgtRefGL) db.restore() db.translate(TAB_WIDTH, 0) db.restore() prog.update() quota -= TAB_LINE_HEIGHT if quota <= PDF_MARGIN: quota = self._initPage(twoLinesFontStyles) prog.setTickCount(value=None) prog.update(text='{}: saving PDF...'.format(caption)) db.saveImage(reportPath) db.endDrawing() except Exception as error: prog.close() raise error prog.close()
def answerSlide(canvasWidth, canvasHeight, answer, polarity): background_fill = polarityBackground(polarity) db.newPage(canvasWidth, canvasHeight) db.fill(*background_fill) db.rect(0, 0, canvasWidth, canvasHeight) db.frameDuration(4) background_images = os.listdir('background_images/') background_image_path = 'background_images/' + background_images[(int)( len(background_images) * random.random())] # https://forum.drawbot.com/topic/180/how-do-i-size-an-image-with-the-imageobject-or-without/4 srcWidth, srcHeight = db.imageSize(background_image_path) dstWidth, dstHeight = canvasWidth - 50, canvasHeight - 50 factorWidth = dstWidth / srcWidth factorHeight = dstHeight / srcHeight with db.savedState(): db.translate(25, 25) with db.savedState(): db.scale(factorWidth, factorHeight) db.image(background_image_path, (0, 0)) db.fill(*rgba(*background_fill, 0.1)) box_width = 0.7 * canvasWidth box_height = canvasHeight * 0.7 x_0 = (canvasWidth - box_width) / 2 y_0 = (canvasHeight - box_height) / 2 - 100 text_box_margin = 40 text_box_width = box_width - text_box_margin * 2 text_box_height = box_height - text_box_margin * 2 current_font_size = 10 db.font('Calibri-Bold', current_font_size) # this is not efficient. Don't show anyone I made this while True: db.fontSize(current_font_size) current_font_size += 1 _, current_text_height = db.textSize(answer, 'left', width=text_box_width) if (current_font_size > 150): break elif (current_text_height > text_box_height): current_font_size -= 2 break db.fontSize(current_font_size) db.stroke(*background_fill) db.strokeWidth(0.5) db.fill(*rgb(255, 252, 61)) db.textBox(answer, (x_0, y_0, box_width, box_height), 'left') # dril says d_says = db.FormattedString() d_says.append("@dril says:", font="Calibri-Bold", fontSize=100, fill=rgb(255, 252, 61), stroke=background_fill, strokeWidth=2) # db.shadow((0,0), 50, background_fill) db.text(d_says, (x_0, y_0 + box_height + 30))
d.drawPath(path) d.newPage(paperSize) # blank page # 4 Typeset text using the glyphs file as if the instance is already installed d.newPage(paperSize) d.fill(0, 0, 0, 1) tempFolder = os.path.expanduser("~/Library/Application Support/Glyphs/Temp") ins = f.instances[ 0] # the index of the instance you want. First instance is 0. f.instances[insIndex].generate( FontPath=tempFolder) # generates the instance in the "Temp" folder. fontPath = "%s/%s" % (tempFolder, ins.fileName()) txt = d.FormattedString() fontName = d.installFont( fontPath ) # Drawbot installes the generated font temporalily. You need to uninstall later in the script. txt.font(fontName) string = """Mary had a little lamb, Its fleece was white as snow, And every where that Mary went The lamb was sure to go.""" fontSize = 48 txt.fontSize(fontSize) txt.lineHeight(fontSize * 1.5) txt.append(string) d.textBox(txt, (margin, margin, d.width() - margin * 2, d.height() - margin)) d.uninstallFont(fontPath) # uninstalls the font from Drawbot
print(fontname, "Calculated font size:", fontsize) target_dir = os.path.join(what, code) if not os.path.exists(target_dir): os.makedirs(target_dir) with open(path, mode="r") as f: for sample in f.readlines(): sample = sample.strip() if sample != "": db.newDrawing() db.newPage(w, h) p = db.BezierPath() db.fill(1) db.stroke(None) db.rect(0, 0, w, h) db.fill(0) # produce SVGs with the text converted # to outlines fs = db.FormattedString(sample, font=fontname, fontSize=fontsize) p.text(fs, (w / 2, h_offset), align="center") db.drawPath(p) db.saveImage(os.path.join(target_dir, sample + ".svg")) tw, _ = db.textSize(fs) if tw > (w - 2 * margin): print("Text '%s' in typeface %s is too wide." % (sample, code)) # save Javascript code with open("sequences.js", "w") as jsf: jsf.write("\n".join(script))