def font(self, fontName, fontSize=None): """Set the context to this selected font name >>> context = DrawBotContext() >>> context.font('Georgia', 12) """ drawBot.font(fontName, fontSize)
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())
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})
def drawContour(self): color = self.colorScheme.colorsRGB['contour'] drawBot.save() drawBot.fontSize(self.captionSize) drawBot.font(self.captionFont) for char in self.txt: uni = ord(char) glyphName = UV2AGL.get(uni) # interpolate g1 = self.font[glyphName].getLayer('regular') g2 = self.font[glyphName].getLayer('bold') glyph = RGlyph() glyph.name = g1.name glyph.unicode = g1.unicode glyph.interpolate(self.interpolationFactor, g1, g2) # draw contours drawBot.stroke(*color) drawBot.strokeWidth(self.contourStrokeWidth) drawBot.fill(None) B = drawBot.BezierPath() for contour in glyph.contours: contour.draw(B) drawBot.drawPath(B) # done glyph drawBot.translate(glyph.width, 0) drawBot.restore()
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})
def typeQualities(isBold=False): fill(*BLACK) stroke(None) openTypeFeatures(tnum=True) if not isBold: font('.SFNS-Regular', 9) else: font('.SFNS-Bold', 9)
def fontLineHeight(self, font=None, fontSize=None): """Returns the current line height, based on the current font and fontSize. If a lineHeight is set, this value will be returned.""" if font is not None: drawBot.font(font) if fontSize is not None: drawBot.fontSize(fontSize) return fontLineHeight()
def fontAscender(self, font=None, fontSize=None): """Returns the current font ascender, based on the current font and fontSize.""" if font is not None: drawBot.font(font) if fontSize is not None: drawBot.fontSize(fontSize) return drawBot.fontAscender()
def fontCapHeight(self, font=None, fontSize=None): """Returns the current font cap height, based on the current font and fontSize.""" if font is not None: drawBot.font(font) if fontSize is not None: drawBot.fontSize(fontSize) return drawBot.fontCapHeight()
def fontLeading(self, font=None, fontSize=None): """Returns the current font leading, based on the current font and fontSize.""" if font is not None: drawBot.font(font) if fontSize is not None: drawBot.fontSize(fontSize) return drawBot.fontLeading()
def _initPage(self, fontStyles): db.newPage('A3Landscape') db.fontSize(BODY_SIZE_TEXT) quota = db.height() - PDF_MARGIN self._drawHeader(quota, fontStyles) db.font('LucidaGrande') quota -= TAB_LINE_HEIGHT * 2 return quota
def drawGlyph(self): color = self.colorScheme.colorsRGB['glyph'] drawBot.save() drawBot.fontSize(self.captionSize) drawBot.font(self.captionFont) for char in self.txt: uni = ord(char) glyphName = UV2AGL.get(uni) # interpolate g1 = self.font[glyphName].getLayer('regular') g2 = self.font[glyphName].getLayer('bold') glyph = RGlyph() glyph.name = g1.name glyph.unicode = g1.unicode glyph.interpolate(self.interpolationFactor, g1, g2) # contours drawBot.fill(*color) B = drawBot.BezierPath() for contour in glyph.contours: contour.draw(B) drawBot.drawPath(B) # advance width if self.glyphWidthDraw: drawBot.save() drawBot.strokeWidth(self.glyphWidthStrokeWidth) drawBot.stroke(*color) drawBot.line((0, self.yBottom), (0, self.yTop)) drawBot.restore() # glyph data if self.glyphDataDraw: h = self.captionSize * 1.5 m = 40 w = glyph.width - m * 2 drawBot.save() drawBot.stroke(None) drawBot.fill(*color) y = self.yTop - h drawBot.textBox(glyph.name, (m, y, w, h)) drawBot.textBox(str(glyph.unicode), (m, y, w, h), align='right') y = self.yBottom drawBot.textBox(str(int(glyph.width)), (m, y, w, h), align='center') drawBot.restore() # done glyph drawBot.translate(glyph.width, 0) # last margin if self.glyphWidthDraw: drawBot.strokeWidth(self.glyphWidthStrokeWidth) drawBot.stroke(*color) drawBot.line((0, self.yBottom), (0, self.yTop)) # done drawBot.restore()
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
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)
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))
def _drawHeader(self, quota, fontStyles): fontTitles = {} colIndex = int(COLS['template'] / TAB_WIDTH) for eachFontStyle in fontStyles: colIndex += 1 fontTitles[eachFontStyle] = colIndex * TAB_WIDTH headers = {k: v for (k, v) in COLS.items() + fontTitles.items()} db.font('LucidaGrande-Bold') for eachTitle, eachX in headers.items(): db.text(eachTitle, (PDF_MARGIN + eachX, quota))
def draw(self, pages: list, export=False): if not pages: return tbs = self.w.customPages.page.textBoxList.getSelection() db.newDrawing() for page in pages: if page is None: continue db.newPage(*page.size) db.save() db.fill(*page.backgroundColor) db.rect(0, 0, *page.size) db.restore() for i, textbox in enumerate(page.textBoxes): db.save() db.translate(*textbox.position[:2]) if not export: db.save() db.fill(None) if i in tbs: db.stroke(1, 0, 0, 1) if not textbox.text: db.fill(.5, .5, .5, .5) db.rect(0, 0, *textbox.position[2:]) db.restore() if textbox.type == "Text": db.save() db.fill(*textbox.color) db.tracking(textbox.tracking) db.font(textbox.font, textbox.fontSize) db.textBox(textbox.text, (0, 0, *textbox.position[2:]), textbox.align) db.restore() elif textbox.type == "UfoText": db.save() db.fill(*textbox.color) s = textbox.fontSize / 1000 db.scale(s, s) for pos, glyph in textbox.glyphs: db.save() db.translate(*pos) if export: glyph.round() db.drawGlyph(glyph) db.restore() db.restore() db.restore() pdfData = db.pdfImage() self.w.customPages.canvas.setPDFDocument(pdfData)
def drawTwoColumnsLayout(txt, postscriptFontName): typeAttributes() text(f'{postscriptFontName} 9 pts', (MARGIN_X1, height() - 25 * FROM_MM_TO_PT)) font(postscriptFontName, FONT_SIZE_PAR_SMALL) textBox(f'{txt}', (BOX1)) typeAttributes() text(f'{postscriptFontName} 12 pts', (MARGIN_X1 * 8, height() - 25 * FROM_MM_TO_PT)) font(postscriptFontName, FONT_SIZE_PAR_MED) textBox(f'{txt}', (BOX2)) # we don't aknowledge overflow, so we return an empty string return ""
def drawInfo(self): color = self.colorScheme.colorsRGB['info'] drawBot.save() # font info if self.infoValuesDraw: drawBot.fill(*color) drawBot.fontSize(self.captionSizeLarge) h = self.captionSizeLarge * 2 y = self.yTop txt = '%s %s' % (self.font.info.familyName, self.font.info.styleName) drawBot.textBox(txt, (0, y, self.textLength, h)) # blue zones # for i, y in enumerate(self.font.info.postscriptBlueValues): # if not i % 2: # yNext = self.font.info.postscriptBlueValues[i+1] # h = yNext - y # drawBot.fill(*color + (0.35,)) # drawBot.rect(0, y, self.textLength, h) # vertical dimensions yValues = set([ 0, self.font.info.xHeight, self.font.info.capHeight, self.font.info.descender, self.font.info.ascender, ]) drawBot.font(self.captionFont) drawBot.fontSize(self.captionSize) for y in yValues: # draw guide drawBot.stroke(*color) drawBot.strokeWidth(self.infoStrokeWidth) if not self.infoLineDash: drawBot.lineDash(None) else: drawBot.lineDash(*self.infoLineDash) drawBot.line((0, y), (self.textLength, y)) # draw y value if self.infoValuesDraw: w = 300 m = 50 drawBot.save() drawBot.stroke(None) drawBot.fill(*color) drawBot.textBox(str(int(y)), (-w-m, y-self.captionSize*0.5, w, self.captionSize*1.2), align='right') drawBot.restore() # done drawBot.restore()
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 test_openTypeFeatures(self): drawBot.newDrawing() fea = drawBot.listOpenTypeFeatures() self.assertEqual(fea, ['liga']) drawBot.font("Helvetica") fea = drawBot.listOpenTypeFeatures() self.assertEqual(fea, ['liga', 'pnum', 'tnum']) fea = drawBot.listOpenTypeFeatures("HoeflerText-Regular") self.assertEqual(fea, ['dlig', 'liga', 'lnum', 'onum', 'pnum', 'titl', 'tnum']) fea = drawBot.openTypeFeatures(liga=False) self.assertEqual(fea, {'liga': False}) drawBot.font("LucidaGrande") fea = drawBot.openTypeFeatures(resetFeatures=True) self.assertEqual(fea, {})
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}})
def drawGuideline(self): color = self.colorScheme.colorsRGB['guideline'] drawBot.save() drawBot.stroke(*color) drawBot.strokeWidth(self.guidelineStrokeWidth) drawBot.font(self.captionFont) drawBot.fontSize(self.captionSize) for guide in self.font.guidelines: drawBot.line((0, guide.y), (self.textLength, guide.y)) if self.guidelineValuesDraw: w = 300 m = 50 drawBot.save() drawBot.stroke(None) drawBot.fill(*color) drawBot.textBox(str(int(guide.y)), (-(w + m), guide.y - self.captionSize * 0.5, w, self.captionSize * 1.2), align='right') drawBot.restore() drawBot.restore()
def makeGlyphSet(self, page): pw = page.w - 2 * PAD # Usable page width ph = page.h - 2 * PAD # Usable page height fs = Text.FS('', **glyphStyle) drawBot.font(self.font) #glyphNames = [] #for glyphName in drawBot.listFontGlyphNames(): # glyphNames.append(glyphName) # glyphNames.append('space') glyphNames = drawBot.listFontGlyphNames() fs.appendGlyph(*glyphNames) pc = 0 while pc < 4 and fs: if pc > 0: page = typeSpecimen.newPage() self.initializePage(page) e = TextBox(fs, x=PAD, y=PAD + 8, w=pw, h=ph - 24, fill=1) page.addElement(e) fs = e.getOverflow(fs, w=PAD, h=ph - 24, doc=self) pc += 1
def makeGlyphSet(self, page, font): """Fill the (self.w, self.h) with a number of children TextBoxes, positioned in lines and spaced by fixed distance, using the glyph width, ignore kerning. Some visual options: - For every font in self.fonts, show the glyph set. - Glyphset by cmap of the font, or by string or random selection. - Glyph can be black or random selection of a set of colors. - Layout in a fixed width/height grid, or as wrapping lines. - Size of the glyph boxes is fixed (number in width/height that fit on the page) or fixed amount that scales to fit. """ pw = page.w - 2 * PAD # Usable page width ph = page.h - 2 * PAD # Usable page height drawBot.font(font) # Set the font to DrawBot current glyphNames = drawBot.listFontGlyphNames( ) # so we can get the set of glyph names. tracking = glyphStyle[ 'fontSize'] / 4 # Extra fixed space between the glyphs. leading = 1.3 # Leading between the lines x = y = 0 # Start at top left of the page (our y goes down). for glyphName in glyphNames: # All glyph names in the current font fs = Text.FS( '', **glyphStyle) # Make a new FormattedStringin this style fs.appendGlyph(glyphName) # And add the current glyph name to it. tw, th = drawBot.textSize( fs) # Measure the size of the FormattedString e = Text(fs, x=x + PAD, y=ph - y) # Text element with single glyph page.addElement(e) # And add it to the page x += tw + tracking # Calculate the horizontal position of the next box if x > pw - PAD: # If it runs over the right padding of the page x = 0 # Start on the left of the next line y += glyphStyle[ 'fontSize'] * leading # New vertical position of the line if y > ph - glyphStyle[ 'fontSize'] * leading: # If vertical is running over bottom page = typeSpecimen.newPage() # Then create a new page self.initializePage(page, font) # and initialize it. x = y = 0 # Reset the position, starting on top-left of the new page.
def introSlide(canvasWidth, canvasHeight, question): db.newPage(canvasWidth, canvasHeight) backgroundImage(canvasWidth, canvasHeight) db.fill(*rgb(94, 174, 235)) # db.rect(0, 0, canvasWidth, canvasHeight) backgroundSquares(canvasWidth, canvasHeight) db.frameDuration(2) db.fill(1, 1, 1) margin_bottom = 0.1 * canvasHeight margin_sides = 0.1 * canvasHeight text_box_margin = margin_sides * 0.5 text_box_width = canvasWidth - margin_sides * 2 - text_box_margin * 2 text_box_height = canvasHeight - margin_sides - margin_bottom - text_box_margin * 2 current_font_size = 10 db.font('ArialNarrow-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(question, 'center', width=text_box_width) # print(current_text_height) # print(text_box_height) if (current_font_size > 150): break elif (current_text_height > text_box_height): current_font_size -= 2 break db.fontSize(current_font_size) db.fill(*rgb(255, 252, 61)) db.textBox(question, (margin_sides + text_box_margin, margin_bottom + text_box_margin, text_box_width, text_box_height), 'center')
def test_ttc_IndexError(self): src = pathlib.Path( __file__).resolve().parent / "data" / "MutatorSans.ttc" self.assertEqual("MutatorMathTest-LightCondensed", drawBot.font(src, fontNumber=0)) self.assertEqual("MutatorMathTest-LightWide", drawBot.font(src, fontNumber=1)) self.assertEqual("MutatorMathTest-BoldCondensed", drawBot.font(src, fontNumber=2)) self.assertEqual("MutatorMathTest-BoldWide", drawBot.font(src, fontNumber=3)) with self.assertRaises(IndexError): drawBot.font(src, fontNumber=4) with self.assertRaises(IndexError): drawBot.font(src, fontNumber=-1)
def drawSegment(self): color = self.colorScheme.colorsRGB['segment'] r = self.bPointSize * 0.5 drawBot.save() drawBot.fontSize(self.captionSize) drawBot.font(self.captionFont) for char in self.txt: uni = ord(char) glyphName = UV2AGL.get(uni) # interpolate g1 = self.font[glyphName].getLayer('regular') g2 = self.font[glyphName].getLayer('bold') glyph = RGlyph() glyph.name = g1.name glyph.unicode = g1.unicode glyph.interpolate(self.interpolationFactor, g1, g2) # draw segment contours drawBot.stroke(*color) drawBot.strokeWidth(self.segmentStrokeWidth) drawBot.fill(None) B = drawBot.BezierPath() glyph.draw(B) drawBot.drawPath(B) # draw segment points drawBot.stroke(None) drawBot.fill(*color) for x, y in B.onCurvePoints: drawBot.oval(x - r, y - r, r * 2, r * 2) drawBot.translate(glyph.width, 0) drawBot.restore()
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 makeSingleTextBoxGlyphSet(self, page, font): """Old version with a single TextBox TODO: Overflow does not seem to work right: only first glyph is cut. """ pw = page.w - 2 * PAD # Usable page width ph = page.h - 2 * PAD # Usable page height fs = Text.FS('', **glyphStyle) drawBot.font(self.font[0]) # Just take the first one of the list #glyphNames = [] #for glyphName in drawBot.listFontGlyphNames(): # glyphNames.append(glyphName) # glyphNames.append('space') glyphNames = drawBot.listFontGlyphNames() fs.appendGlyph(*glyphNames) pc = 0 while pc < 4 and fs: if pc > 0: page = typeSpecimen.newPage() self.initializePage(page) e = TextBox(fs, x=PAD, y=PAD + 8, w=pw, h=ph - 24, fill=1) page.addElement(e) fs = e.getOverflow(fs, w=PAD, h=ph - 24, doc=self) pc += 1
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 test_openTypeFeatures_saveRestore(self): drawBot.newDrawing() drawBot.font("AppleBraille") drawBot.save() drawBot.restore()
import drawBot drawBot.size(200, 200) drawBot.text("hello world", (10, 10)) drawBot.fill(1, 0, 0) drawBot.text("foo bar", (10, 30)) drawBot.fill(1, 0, 1) drawBot.stroke(0, 1, 0) drawBot.strokeWidth(4) drawBot.font("Times", 50) drawBot.text("foo bar", (10, 50)) drawBot.fill(None) drawBot.stroke(0, 1, 0) drawBot.strokeWidth(1) drawBot.line((0, 50), (drawBot.width(), 50)) drawBot.stroke(None) drawBot.fill(0, 1, 1) drawBot.fontSize(20) drawBot.text("foo bar", (drawBot.width()*.5, 100), align="right") drawBot.text("foo bar", (drawBot.width()*.5, 120), align="center") drawBot.text("foo bar", (drawBot.width()*.5, 140), align="left")