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 fontSize(self, fontSize): """Set the context to this selected font name >>> context = DrawBotContext() >>> context.fontSize(12) """ drawBot.fontSize(fontSize)
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 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 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 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 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 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 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 test_imageAntiAliasing(self): from testScripts import DrawBotTest expectedPath = os.path.join(testDataDir, "expected_imageAntiAliasing.png") drawBot.newDrawing() drawBot.size(100, 100) drawBot.fill(1, 0, 0) drawBot.oval(10, 10, 40, 80) drawBot.fill(0) drawBot.stroke(0) drawBot.line((-0.5, -0.5), (100.5, 100.5)) drawBot.line((0, 20.5), (100, 20.5)) drawBot.fontSize(20) drawBot.text("a", (62, 30)) with TempFile(suffix=".png") as tmp: drawBot.saveImage(tmp.path, antiAliasing=False) self.assertImageFilesEqual(tmp.path, expectedPath)
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 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()
with open(path, mode="r") as f: for sample in f.readlines(): sample = sample.strip() if sample != "": script.append(" '%s'," % sample) if what == "practice": script.append("];\n\n") elif what == "non-word": script.append("]];\n\n") # generate SVGs for code, fontname, h_offset in typefaces[what]: db.font(fontname) # increase fontsize to match x-height to ca 1/6 of the page height fontsize = 20 db.fontSize(fontsize) xh = db.fontXHeight() while xh < h / 6: fontsize += 1 db.fontSize(fontsize) xh = db.fontXHeight() 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)
def fontSize(self, fontSize): drawBot.fontSize(fontSize)
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))
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")
import os import drawBot drawBot.size(50, 50) characters = "Aa今" glyphNames = ["A", "a", "zzz"] for fontName in ["Helvetica", "../data/MutatorSans.ttf"]: print(fontName) print(drawBot.font(fontName)) drawBot.fontSize(50) for char in characters: print(drawBot.fontContainsCharacters(char)) for glyphName in glyphNames: print(drawBot.fontContainsGlyph(glyphName)) print(os.path.basename(drawBot.fontFilePath())) print(drawBot.listFontGlyphNames()[:6]) print(drawBot.fontAscender()) print(drawBot.fontDescender()) print(drawBot.fontXHeight()) print(drawBot.fontCapHeight()) print(drawBot.fontLeading()) print(drawBot.fontLineHeight()) print() for i in range(4): print(drawBot.font("../data/MutatorSans.ttc", fontNumber=i)) print(os.path.basename(drawBot.fontFilePath()), drawBot.fontFileFontNumber()) assert drawBot.fontFileFontNumber() == i print() for fontName in ["Courier", "Courier-Bold", "Courier-Oblique"]:
# 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()
# 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 draw(self, sender): if len(self.loadedFontList) == 0: self.w.amountOfLoadedFonts.set("!!! --->") return glyphNames = self.glyphNamesInputCheck() #pageWidth = self.w.pageWidth.get() pageHeight = int(self.w.pageHeight.get()) pageWidth = pageHeight extraSpace = float(self.w.canvasMargin.get()) countForTransparency = 0 try: import drawBot except: Message("Missing Module", "Please install DrawBot") return drawBot.newDrawing() tickCount = (len(glyphNames) * int(str(self.w.speed.get()))) * len( self.loadedFontList) tick = 0 #progressBar = ProgressBar(title="", ticks=tickCount, label="generating .gifs ...") for i, glyphName in enumerate(glyphNames): tick = tick + 1 #progressBar.tick(tick) for thisFontPath in self.loadedFontList: thisFont = Glyphs.open(thisFontPath, False) selectionMaster = thisFont.masters[0].id master = thisFont.masters[0] tick = tick + 1 #progressBar.tick(tick) countForTransparency += 1 # RF # UPM = thisFont.info.unitsPerEm # descender = thisFont.info.descender # GlyphsApp #xHeight = thisFont.info.xHeight #capHeight = thisFont.info.capHeight #ascender = thisFont.info.ascender UPM = thisFont.upm descender = master.descender sc = pageHeight / ((UPM) * extraSpace) for index in range(int(str(self.w.speed.get()))): tick = tick + 1 #progressBar.tick(tick) drawBot.newPage(pageWidth, pageHeight) ############ START Drawing BG drawBot.save() # getting colors (including Random if used) glyphFillColor = self._colorization( countForTransparency)[0] glyphStrokeColor = self._colorization( countForTransparency)[1] backgroundColor = self._colorization( countForTransparency)[2] # draw background # draw additional BLACK background if Background Transparency fade is active if self.w.BTransparency.get() == 1: drawBot.fill(self.w.BGtransparentColor.get()) drawBot.rect(0, 0, pageWidth, pageWidth) else: drawBot.fill(1, 1, 1, 1) drawBot.rect(0, 0, pageWidth, pageWidth) drawBot.fill(*backgroundColor) drawBot.rect(0, 0, pageWidth, pageWidth) ############### END Drawing BG ## ONLY IF THE GLYPH EXISTS IN FONT: DRAW GLYPH # RF #if glyphName in thisFont.keys(): if thisFont.glyphs[glyphName] is not None: glyph = thisFont.glyphs[glyphName].layers[ selectionMaster] #RF #glyph = thisFont[glyphName] ############ START Glyph(s) # set scale/shift for drawing glyph(s) to pagesize drawBot.scale(sc) translateY = -descender + (int( str(self.w.yShiftGlyph.get()))) translateX = ((pageHeight / sc) - glyph.width) / 2 drawBot.translate(translateX, translateY) # set colors for fill and stroke and Stroke thickness of Glyph Drawing drawBot.stroke(*glyphStrokeColor) drawBot.strokeWidth( int(str(self.w.strokeThickness.get()))) drawBot.fill(*glyphFillColor) ## GlyphsApp drawBot.drawPath(glyph.completeBezierPath) # RF drawGlyph #self._drawGlyph(glyph) ## if the glyph doesn't exist: DRAW ONLY BACKGROUND else: print(glyphName, "glyph doesn't exist in one of the fonts!") drawBot.restore() ############### END Glyph(s) ############### START title and time stamp stamp = self.AddStamp(thisFont) if len(stamp) == 0: pass else: save() x, y, w, h = 0, 5, int(self.w.pageHeight.get()), 10 fill(self.w.titleColor.get()) #fill(1, 0, 0, 0.2) drawBot.fontSize(7) overflow = textBox(" ".join(stamp).strip(" "), (x, y, w, h), align="center") drawBot.restore() ############### END title and time stamp exportstring = str( os.path.expanduser('~')) + "/Desktop/" + glyphName + ".gif" ## check if file exists - in order not to write a new file instead of overwriting it. PATH = os.path.expanduser('~') + "/Desktop/" + glyphName + ".gif" if path.isfile(PATH) == True: now = datetime.datetime.now() date = "_%d-%d-%d_%dh-%dm-%ds" % (now.day, now.month, int(str(now.year)[2:]), now.hour, now.minute, now.second) exportstring = str(os.path.expanduser( '~')) + "/Desktop/" + glyphName + date + ".gif" drawBot.saveImage([exportstring])
for n in p.nodes: if n.type == GSLINE: corners.append(n) elif n.type == GSCURVE and n.connection == 0: corners.append(n) radius = 3 d.fill(None) d.stroke(0, 1, 0, 1) for c in corners: d.rect(c.x - radius, c.y - radius, radius * 2, radius * 2) # draw anchors as circles radius = 5 d.fill(1, 0.5, 0, 1) # set orange colour for fill d.stroke(0, 0, 1, 0.5) # set semi-transparent blue for stroke d.fontSize(12) for a in l.anchors: d.oval(a.x - radius, a.y - radius, radius * 2, radius * 2) d.text(a.name, (a.x, a.y + 10)) # anchor name while I'm at it d.newPage(paperSize) # blank page # 3 The size and position were probably wrong. Let's fix that by using the font metrics. margin = 32 # it's in 0.5 mm increment. 32 = 16 mm bodyHeightOnPaper = d.height( ) - margin * 2 # vertical size of the paper, minus top & bottom margin scale = bodyHeightOnPaper / (m.ascender - m.descender) for l in sel: d.newPage(paperSize) # get position and scale right
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 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]))