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 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 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 draw(self, origin, view): u"""Draw the text on position (x, y). Draw background rectangle and/or frame if fill and/or stroke are defined.""" p = pointOffset(self.oPoint, origin) p = self._applyScale(p) px, py, _ = p = self._applyAlignment(p) # Ignore z-axis for now. # TODO: Add marker if there is overflow text in the textbox. self.drawFrame(p, view) # Draw optional frame or borders. if self.drawBefore is not None: # Call if defined self.drawBefore(self, p, view) # Draw the text with horizontal and vertical alignment tw, th = textSize(self.fs) xOffset = yOffset = 0 if self.css('yTextAlign') == MIDDLE: yOffset = (self.h - self.pb - self.pt - th) / 2 elif self.css('yTextAlign') == BOTTOM: yOffset = self.h - self.pb - self.pt - th if self.css('xTextAlign') == CENTER: xOffset = (self.w - self.pl - self.pr - tw) / 2 elif self.css('xTextAlign') == RIGHT: xOffset = self.w - self.pl - self.pr - tw textShadow = self.textShadow if textShadow: save() setShadow(textShadow) textBox(self.fs, (px + self.pl + xOffset, py + self.pb - yOffset, self.w - self.pl - self.pr, self.h - self.pb - self.pt)) if textShadow: restore() # If there are any child elements, draw them over the text. self._drawElements(p, view) # Draw markers on TextLine and TextRun positions. self._drawBaselines(px, py, view) if view.showTextOverflowMarker and self.isOverflow(): self._drawOverflowMarker(px, py, view) if self.drawAfter is not None: # Call if defined self.drawAfter(self, p, view) self._restoreScale() view.drawElementMetaInfo( self, origin) # Depends on css flag 'showElementInfo'
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 drawFont(self): color = self.colorScheme.colorsRGB['font'] drawBot.save() drawBot.fill(*color) drawBot.fontSize(self.captionSizeLarge) h = self.captionSizeLarge * 2 m = 20 y = self.yBottom - h - 20 txt = 'FontParts-Sans.ufo' # txt += f' ({len(self.font.layerOrder)} layers)' # txt += f' ({len(self.font)} glyphs)' # txt += '%s contours / %s points ' % countContoursPoints(self.font) drawBot.textBox(txt, (0, y, self.textLength, h), align='center') drawBot.restore()
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 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 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 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 drawWeight(weight, text): db.newDrawing() self.designFrameViewer.draw() db.newPage(FRAMEX, FRAMEY) db.textBox(user, (0, FRAMEY - 85, FRAMEX, 55), align='center') db.textBox(text, (0, FRAMEY - 105, FRAMEX, 55), align='center') s = .11 tx, ty = (FRAMEX / s - 1000 * 4) * .5, 1000 * 5.8 db.save() db.scale(s, s) db.translate(tx, ty) db.fontSize(60) print(weight) for i, glyph in enumerate(weight): drawDesignFrame() if glyph[0].markColor: db.fill(*glyph[0].markColor) else: db.fill(*INPROGRESS) db.rect(0, 900, 250, 100) db.fill(0, 0, 0, 1) db.stroke(None) db.textBox(glyph[0].name, (0, 900, 1000, 100), align="center") db.fill(0, 0, 0, 1) db.stroke(None) for c in glyph: db.drawGlyph(c) if (i + 1) % 4: db.translate(1000, 0) else: db.translate(-1000 * 3, -1200) db.restore() pdfData = db.pdfImage() now = datetime.datetime.now() if not self.RCJKI.currentFont.mysql: outputPath = os.path.join( self.RCJKI.currentFont.fontPath, "Proofing", user, '%s_%s_%s.pdf' % (date, str(pageIndex).zfill(2), text)) else: outputPath = os.path.join( mysqlpath, '%s_%s_%s.pdf' % (date, str(pageIndex).zfill(2), text)) # os.rename(outputPath, outputPath[:-3]+'ai') files.makepath(outputPath) db.saveImage(outputPath) os.rename(outputPath, outputPath[:-3] + "ai")
def getOverflow(self, fs=None, w=None, h=None, doc=None): """Flow the text into self and put any overflow in self.next. If there is no self.next defined, then store the remaining overflow text in self.overflow. """ # If another FormattedString is defined, then use that. # Otherwise use the existing self.fs if fs is None: fs = self.fs # Since we cannot test the overflow without drawing in DrawBot, we'll # create a text column far outside the page boundaries. # Unfortunately this increases the PDF export size. h = w or self.h w = h or self.w if h is None and w is not None: # Height of the box is undefined, measure it from the defined column width. _, h = drawBot.textSize(fs, width=w) elif w is None and h is not None: # Width of the box is undefined, measure it from the defined column height. w, _ = drawBot.textSize(fs, height=h) # Height of the box is undefined, measure it from the defined column width. return drawBot.textBox(fs, (10000, 0, w, h))
def drawContent(self, ox, oy, doc, page, parent): """We just need to define drawing of the foreground. The rest of behavior for the Text element (including drawing on the background) is handled by the base Element class. """ # Store any overflow to be processed by the caller. # Note that this should never happen, as the context of the text box # better can be processed by self.flowText before any drawing is done. # It is assumed that self.h is set, otherwise take the height of the # text column that fits all text. h = self.h w = self.w if h is None and w is not None: # Height of the box is undefined, measure it from the defined column width. _, h = drawBot.textSize(self.fs, width=w) elif w is None and h is not None: # Width of the box is undefined, measure it from the defined column height. w, _ = drawBot.textSize(self.fs, height=h) # Else if width and height are both defined or undefined, we can used them as is. # In case width and height are both defined, it may result in a new overflow # FormattedString. Store that in self.overflow. self.overflow = drawBot.textBox(self.fs, (ox, oy, self.w, self.h or page.h))
def draw(self): user = self.RCJKI.gitUserName now = datetime.datetime.now() date = "%s%s%s_%s%s%s" % (now.year, str( now.month).zfill(2), str(now.day).zfill(2), str( now.hour).zfill(2), str(now.minute).zfill(2), str( now.second).zfill(2)) if self.RCJKI.currentFont.mysql: mysqlpath = vanilla.dialogs.getFolder()[0] def drawDesignFrame(): for e in self.designFrameViewer.elements: glyph, color, type = e if type == 'stroke': db.stroke(*color) db.fill(None) else: db.stroke(None) db.fill(*color) db.drawGlyph(glyph) for pageIndex, page in enumerate(self.pages): db.newDrawing() self.designFrameViewer.draw() glyphsVariations = {} # light = [] db.newPage(FRAMEX, FRAMEY) db.textBox(user, (0, FRAMEY - 85, FRAMEX, 55), align='center') db.textBox('%s-Overlay' % self.RCJKI.currentFont.fontName, (0, FRAMEY - 105, FRAMEX, 55), align='center') s = .11 tx, ty = (FRAMEX / s - 1000 * 4) * .5, 1000 * 5.8 db.save() db.scale(s, s) db.translate(tx, ty) db.fontSize(60) for i, glyph in enumerate(page): name = glyph.name try: for variation in self.RCJKI.currentFont.fontVariations: glyph1 = glyph if variation not in glyphsVariations.keys(): glyphsVariations[variation] = [] resultGlyph = [] for c in glyph1.preview({variation: 1}): c = c.glyph c.markColor = glyph1.markColor c.name = glyph1.name resultGlyph.append(c) glyphsVariations[variation].append(resultGlyph) drawDesignFrame() if glyph1.markColor: db.fill(*glyph1.markColor) else: db.fill(*INPROGRESS) db.rect(0, 900, 250, 100) db.fill(0, 0, 0, 1) db.stroke(None) db.textBox(name, (0, 900, 1000, 100), align="center") db.fill(1, 1, 1, 1) db.stroke(0, 0, 0, 1) db.strokeWidth(1) for c in resultGlyph: db.drawGlyph(c) variation = "normal" if variation not in glyphsVariations.keys(): glyphsVariations[variation] = [] resultGlyph = [] for c in glyph1.preview({variation: 0}): c = c.glyph c.markColor = glyph1.markColor c.name = glyph1.name resultGlyph.append(c) glyphsVariations[variation].append(resultGlyph) for c in resultGlyph: db.drawGlyph(c) if (i + 1) % 4: db.translate(1000, 0) else: db.translate(-1000 * 3, -1200) except Exception as e: raise e db.restore() pdfData = db.pdfImage() if not self.RCJKI.currentFont.mysql: outputPath = os.path.join( self.RCJKI.currentFont.fontPath, "Proofing", user, '%s_%s_%s-%s.pdf' % (date, str(pageIndex).zfill(2), self.RCJKI.currentFont.fontName, "Overlay")) else: outputPath = os.path.join( mysqlpath, '%s_%s_%s-%s.pdf' % (date, str(pageIndex).zfill(2), self.RCJKI.currentFont.fontName, "Overlay")) files.makepath(outputPath) db.saveImage(outputPath) os.rename(outputPath, outputPath[:-3] + "ai") def drawWeight(weight, text): db.newDrawing() self.designFrameViewer.draw() db.newPage(FRAMEX, FRAMEY) db.textBox(user, (0, FRAMEY - 85, FRAMEX, 55), align='center') db.textBox(text, (0, FRAMEY - 105, FRAMEX, 55), align='center') s = .11 tx, ty = (FRAMEX / s - 1000 * 4) * .5, 1000 * 5.8 db.save() db.scale(s, s) db.translate(tx, ty) db.fontSize(60) print(weight) for i, glyph in enumerate(weight): drawDesignFrame() if glyph[0].markColor: db.fill(*glyph[0].markColor) else: db.fill(*INPROGRESS) db.rect(0, 900, 250, 100) db.fill(0, 0, 0, 1) db.stroke(None) db.textBox(glyph[0].name, (0, 900, 1000, 100), align="center") db.fill(0, 0, 0, 1) db.stroke(None) for c in glyph: db.drawGlyph(c) if (i + 1) % 4: db.translate(1000, 0) else: db.translate(-1000 * 3, -1200) db.restore() pdfData = db.pdfImage() now = datetime.datetime.now() if not self.RCJKI.currentFont.mysql: outputPath = os.path.join( self.RCJKI.currentFont.fontPath, "Proofing", user, '%s_%s_%s.pdf' % (date, str(pageIndex).zfill(2), text)) else: outputPath = os.path.join( mysqlpath, '%s_%s_%s.pdf' % (date, str(pageIndex).zfill(2), text)) # os.rename(outputPath, outputPath[:-3]+'ai') files.makepath(outputPath) db.saveImage(outputPath) os.rename(outputPath, outputPath[:-3] + "ai") for variations, weights in glyphsVariations.items(): drawWeight( weights, '%s-%s' % (self.RCJKI.currentFont.fontName, variations)) if not self.RCJKI.currentFont.mysql: textPath = os.path.join( self.RCJKI.currentFont.fontPath, "Proofing", user, '%s_%s_text.txt' % (date, str(pageIndex).zfill(2))) else: textPath = os.path.join( mysqlpath, '%s_%s_text.txt' % (date, str(pageIndex).zfill(2))) files.makepath(textPath) with open(textPath, 'w', encoding='utf-8') as file: file.write("".join([chr(int(x.name[3:], 16)) for x in page]))
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()
def textBox(self, bs, r): bs = BabelString() # Set the cache from the overflow, we don't have the source anymore bs.fs = drawBot.textBox(bs.fs, r) return bs # Return this “incomplete” BabelString.
# db.stroke(0, 0, 0, 1) db.stroke(0.8, 0.8, 0.8, 1) db.fill(1, 1, 1, 1) db.strokeWidth(20) db.lineJoin('round') db.drawPath(sh.getGlyphPath(ufo_path, 'I')) # db.stroke(0.95, 0.95, 0.95, 1) db.drawPath(sh.getGlyphPath(ufo_path, 'J')) db.fill(0.8, 0.8, 0.8, 1) db.stroke(None) db.drawPath(sh.getGlyphPath(ufo_path, 'K')) db.drawPath(sh.getGlyphPath(ufo_path, 'L')) db.restore() db.save() db.font('Tsukushi B Round Gothic Bold', 200) db.fill(0.1) db.lineHeight(100) db.textBox('新謹春賀', (380, 100, 500, 1000)) db.fontSize(46) db.lineHeight(30) # db.textBox('明けましておめでとうございます。', (240, 80, 800, 200)) # db.textBox('本年も良い年でありますように、心よりお祈り申し上げます。', (240, -180, 700, 400)) db.textBox('旧年中は大変お世話になりました。', (240, 80, 800, 200)) db.textBox('皆様のご多幸とご健康をお祈りいたします。', (240, -180, 700, 400)) db.restore() saveImage("/Users/shu/Downloads/pig.png", imageResolution=300) db.endDrawing()
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 filePath = "~/Desktop/aaaaaaa.pdf" d.saveImage(filePath) subprocess.call(["open", "-R", os.path.expanduser(filePath)]) # show the PDF in the Finder
import drawBot f = CurrentFont() s = CurrentFont().selection fontName = '%s-%s' % (f.info.familyName, f.info.styleName) if s is not None: drawBot.newPage('Letter') drawBot.font(fontName) drawBot.fontSize(200) txt = str(s) for char in "[ ' ] ": txt = txt.replace(char, "") drawBot.textBox(txt, (100, 0, drawBot.width() - 60, drawBot.height() - 120), align="left") drawBot.printImage()
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" # Spacing txt += "\n" * 2 for glyphName in txt.listFontGlyphNames(): txt.appendGlyph("n", "n", glyphName, "n", "n", "space") txt.appendGlyph("e", "e", glyphName, "e", "e", "space") while txt: drawBot.newPage("A4Landscape") txt = drawBot.textBox(txt, (40, 40, drawBot.width()-80, drawBot.height()-100)) # Add the date and name of the font psName = drawBot.font(fontURL) drawBot.font("Arial") drawBot.fontSize(11) drawBot.text(psName, (40, 40)) date = datetime.today().strftime("%d/%m/%Y") drawBot.text(date,(drawBot.width()-40,40), align="right") drawBot.saveImage("specimen.pdf") drawBot.endDrawing()
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))
def textBox(self, bs, r): # Set the cache from the overflow, we don't have the source anymore overFlow = BabelString(hyphenation=bs.hyphenation) overFlow.fs = drawBot.textBox(bs.fs, r) return overFlow # Return this “incomplete” BabelString.
def drawOneColumnLayout(txt, postscriptFontName): font(postscriptFontName, FONT_SIZE_LARGE) txt = textBox(f'{txt}', (LARGE)) return txt