示例#1
0
 def test_instructionStack(self):
     expected = [
         "reset None", "newPage 200 200", "save",
         "clipPath moveTo 5.0 5.0 lineTo 15.0 5.0 lineTo 15.0 15.0 lineTo 5.0 15.0 closePath",
         "restore", "image Image Object 10 10 0.5 None",
         "blendMode saturation", "transform 1 0 0 1 10 10",
         "drawPath moveTo 10.0 10.0 lineTo 110.0 10.0 lineTo 110.0 110.0 lineTo 10.0 110.0 closePath",
         "textBox foo bar 72.48291015625 84.0 55.0341796875 26.0 center",
         "frameDuration 10", "saveImage * {'myExtraAgrument': True}"
     ]
     with StdOutCollector() as output:
         import drawBot
         drawBot.newDrawing()
         drawBot.size(200, 200)
         drawBot.save()
         path = drawBot.BezierPath()
         path.rect(5, 5, 10, 10)
         drawBot.clipPath(path)
         drawBot.restore()
         im = drawBot.ImageObject()
         with im:
             drawBot.size(20, 20)
             drawBot.rect(5, 5, 10, 10)
         drawBot.image(im, (10, 10), alpha=.5)
         drawBot.blendMode("saturation")
         drawBot.translate(10, 10)
         drawBot.rect(10, 10, 100, 100)
         drawBot.text("foo bar", (100, 100), align="center")
         drawBot.frameDuration(10)
         drawBot.saveImage("*", myExtraAgrument=True)
         drawBot.endDrawing()
     self.assertEqual(output.lines(), expected)
示例#2
0
    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()
示例#3
0
    def draw(self, origin, view):
        u"""Draw the image in the calculated scale. Since we need to use the image
        by scale transform, all other measure (position, lineWidth) are scaled
        back to their original proportions.
        If stroke is defined, then use that to draw a frame around the image.
        Note that the (sx, sy) is already scaled to fit the padding position and size."""
        p = pointOffset(self.oPoint, origin)   
        p = self._applyScale(p)    
        px, py, _ = self._applyAlignment(p) # Ignore z-axis for now.

        if self.path is None or not os.path.exists(self.path) or not self.iw or not self.ih:
            # TODO: Also show error, in case the image does not exist, to differ from empty box.
            print 'Cannot display pixelMap', self
            #self._drawMissingElementRect(page, px, py, self.w, self.h)
        else:
            save()
            sx = self.w / self.iw
            sy = self.h / self.ih
            scale(sx, sy)
            
            # If there is a clipRect defined, create the bezier path
            if self.clipRect is not None:
                clipRect = BezierPath()
                clX, clY, clW, clH = self.clipRect
                sclX = clX/sx
                sclY = clY/sx
                sclW = clW/sx
                sclH = clH/sy
                # move to a point
                clipRect.moveTo((sclX, sclY))
                # line to a point
                clipRect.lineTo((sclX, sclY+sclH))
                clipRect.lineTo((sclX+sclW, sclY+sclH))
                clipRect.lineTo((sclX+sclW, sclY))
                # close the path
                clipRect.closePath()
                # set the path as a clipping path
                clipPath(clipRect)
                # the image will be clipped inside the path
                #fill(1, 0, 0, 0.5)
                #drawPath(clipRect)
            elif self.clipPath is not None:
                #Otherwise if there is a clipPath, then use it.
                clipPath(self.clipPath)

            if self.imo is not None:
                with self.imo:
                    image(self.path, (0, 0), pageNumber=0, alpha=self._getAlpha())
                image(self.imo, (px/sx, py/sy), pageNumber=0, alpha=self._getAlpha())
            else:
                # Store page element Id in this image, in case we want to make an image index later.
                image(self.path, (px/sx, py/sy), pageNumber=0, alpha=self._getAlpha())
            # TODO: Draw optional (transparant) forground color?
            restore()

        # If there are child elements, draw them over the pixel image.
        self._drawElements(origin, view)

        self._restoreScale()
        view.drawElementMetaInfo(self, origin)
示例#4
0
    def draw(self, origin, view):

        p = pointOffset(self.oPoint, origin)
        p = self._applyScale(p)
        px, py, _ = p = self._applyAlignment(p)  # Ignore z-axis for now.

        save()
        sh = 1.0 * self.h / self.ih
        transform((1, 0, 0, 1, px, py))
        scale(sh)
        if self.pathFilter is not None:
            self.pathFilter(self, self.glyph.path)
        if self.css('fill') != NO_COLOR or self.css('stroke') != NO_COLOR:
            setFillColor(self.css('fill'))
            print(self.css('strokeWidth') or 1), sh
            setStrokeColor(self.css('stroke', NO_COLOR),
                           (self.css('strokeWidth') or 20))
            fill(0)
            stroke(1, 0, 0)
            strokeWidth(20)
            drawPath(self.glyph.path)
        restore()

        # If there are child elements, draw them over the polygon.
        self._drawElements(p, view)

        # Draw optional bounding box.
        #self.drawFrame(origin, view)

        self._restoreScale()
        view.drawElementMetaInfo(
            self, origin)  # Depends on css flag 'showElementInfo'
示例#5
0
def drawGlyphPath(font, glyphName, x, y, s=0.1, fillColor=0, strokeColor=None, strokeWidth=0):
    glyph = font[glyphName]
    save()
    setFillColor(fillColor)
    setStrokeColor(strokeColor, strokeWidth)
    transform((1, 0, 0, 1, x - glyph.width/2*s, y))
    scale(s)
    drawPath(glyph.path)
    restore()
示例#6
0
    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'
示例#7
0
            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")
示例#8
0
    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()
示例#9
0
 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()
示例#10
0
 def drawContent(self, ox, oy, doc, page, parent):
     """We just need to define drawing of the image. The rest of behavior
     for the Image element (including drawing on the background and the frame) 
     is handled by the base Element class.
     """
     # Get the scale of the image, comparing the file size with the size
     # of the image element.
     sx, sy = self.getScale()
     # In drawBot it is not possible to scale the image, so we need to scale
     # the canvas instead. Then also we need to scale the (ox, oy) positions.
     # After drawing, reverse scale the canvas back to 100%
     drawBot.save()
     drawBot.scale(sx, sy)
     drawBot.image(self.path, (ox / sx, oy / sy))
     #drawBot.scale(1/sx, 1/sy)
     drawBot.restore()
示例#11
0
def draw_block(box_size, box_depth, rows, columns, layers):

    box = make_box(box_size, box_depth)

    for column in range(columns):
        db.save()
        db.translate(-column * box_size[0], 0)
        db.drawPath(box)
        for row in range(rows):
            db.save()
            db.translate(0, row * box_size[1])
            db.drawPath(box)
            for layer in range(layers - 1):
                db.translate(math.fabs(box_depth[0]), -math.fabs(box_depth[1]))
                db.drawPath(box)
            db.restore()
        db.restore()
示例#12
0
 def drawComponent(self):
     color = self.colorScheme.colorsRGB['component']
     tempName = '_tmp_'
     drawBot.save()
     for char in self.txt:
         uni = ord(char)
         glyphName = UV2AGL.get(uni)
         glyph = self.font[glyphName]
         drawBot.fill(*color + (0.5,))
         drawBot.stroke(*color)
         if len(glyph.components):
             B = drawBot.BezierPath()
             for component in glyph.components:
                 component.draw(B)
             drawBot.drawPath(B)
         # done glyph
         drawBot.translate(glyph.width, 0)
     drawBot.restore()
示例#13
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()
示例#14
0
 def drawAnchor(self):
     r = self.anchorSize * 0.5
     color = self.colorScheme.colorsRGB['anchor']
     drawBot.save()
     drawBot.strokeWidth(self.anchorStrokeWidth)
     drawBot.stroke(*color)
     drawBot.fill(None)
     for char in self.txt:
         uni = ord(char)
         glyphName = UV2AGL.get(uni)
         glyph = self.font[glyphName]
         if len(glyph.anchors):
             for anchor in glyph.anchors:
                 x, y = anchor.x, anchor.y
                 drawBot.oval(x-r, y-r, r*2, r*2)
                 drawBot.line((x-r, anchor.y), (x+r, anchor.y))
                 drawBot.line((anchor.x, y-r), (anchor.x, y+r))
         drawBot.translate(glyph.width, 0)
     drawBot.restore()
示例#15
0
    def drawBPoint(self):

        r1 = self.bPointSize * 0.5
        r2 = self.pointSize * 0.5

        color = self.colorScheme.colorsRGB['bPoint']
        drawBot.save()
        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)

            for c in glyph.contours:
                for pt in c.bPoints:
                    x, y = pt.anchor
                    xIn,  yIn  = pt.bcpIn
                    xOut, yOut = pt.bcpOut

                    drawBot.fill(*color)
                    drawBot.stroke(None)
                    drawBot.oval(x - r1, y - r1, r1 * 2, r1 * 2)
                    if not self.layers['point']:
                        drawBot.oval(x + xIn - r2, y + yIn - r2, r2 * 2, r2 * 2)
                        drawBot.oval(x + xOut - r2, y + yOut - r2, r2 * 2, r2 * 2)

                    drawBot.fill(None)
                    drawBot.stroke(*color)
                    drawBot.strokeWidth(5)
                    drawBot.line((x, y), (x + xIn, y + yIn))
                    drawBot.line((x, y), (x + xOut, y + yOut))

            drawBot.translate(glyph.width, 0)
        drawBot.restore()
示例#16
0
    def drawLayer(self):

        steps = 3
        alpha = 0.2 + 0.8 / (steps + 1)
        color = self.colorScheme.colorsRGB['layer']

        drawBot.save()

        # drawBot.fill(None)
        # drawBot.stroke(*color)
        # drawBot.strokeWidth(self.layerStrokeWidth)

        color += (alpha,)
        drawBot.fill(*color)
        drawBot.stroke(None)

        for char in self.txt:
            uni = ord(char)
            glyphName = UV2AGL.get(uni)

            g1 = self.font[glyphName].getLayer('regular')
            g2 = self.font[glyphName].getLayer('bold')

            layerGlyphs = []
            for i in range(steps):
                factor = i * 1.0 / (steps - 1)
                g3 = RGlyph()
                g3.name = g1.name
                g3.unicode = g1.unicode
                g3.interpolate(factor, g1, g2)
                layerGlyphs.append(g3)

            for g in layerGlyphs:
                B = drawBot.BezierPath()
                g.draw(B)
                drawBot.drawPath(B)

            drawBot.translate(g2.width, 0)

        drawBot.restore()
示例#17
0
    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()
示例#18
0
    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()
示例#19
0
    def drawPoint(self):
        r = self.pointSize * 0.5
        color = self.colorScheme.colorsRGB['point']
        drawBot.save()
        drawBot.fill(*color)
        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)

            for c in glyph.contours:
                for pt in c.points:
                    x, y = pt.x, pt.y
                    drawBot.oval(x-r, y-r, r*2, r*2)
            drawBot.translate(glyph.width, 0)
        drawBot.restore()
示例#20
0
    def draw(self, pos):
        x, y = pos
        drawBot.save()
        drawBot.translate(x, y)
        drawBot.scale(self.scale)
        if self.layers['font']:      self.drawFont()
        if self.layers['layer']:     self.drawLayer()
        if self.layers['info']:      self.drawInfo()
        if self.layers['guideline']: self.drawGuideline()
        if self.layers['glyph']:     self.drawGlyph()
        if self.layers['font lib']:  self.drawFontLib()
        if self.layers['kerning']:   self.drawKerning()
        if self.layers['features']:  self.drawFeatures()
        if self.layers['glyph lib']: self.drawGlyphLib()
        if self.layers['anchor']:    self.drawAnchor()
        if self.layers['component']: self.drawComponent()
        if self.layers['image']:     self.drawImage()
        if self.layers['contour']:   self.drawContour()
        if self.layers['point']:     self.drawPoint()
        if self.layers['bPoint']:    self.drawBPoint()
        if self.layers['segment']:   self.drawSegment()

        drawBot.restore()
示例#21
0
 def test_instructionStack(self):
     expected = [
         "reset None",
         "newPage 200 200",
         "save",
         "clipPath moveTo 5.0 5.0 lineTo 15.0 5.0 lineTo 15.0 15.0 lineTo 5.0 15.0 closePath",
         "restore",
         "image Image Object 10 10 0.5 None",
         "blendMode saturation",
         "transform 1 0 0 1 10 10",
         "drawPath moveTo 10.0 10.0 lineTo 110.0 10.0 lineTo 110.0 110.0 lineTo 10.0 110.0 closePath",
         "textBox foo bar 82.48291015625 84.0 35.0341796875 26.0 center",
         "frameDuration 10",
         "saveImage * {'myExtraAgrument': True}"
     ]
     with StdOutCollector() as output:
         import drawBot
         drawBot.newDrawing()
         drawBot.size(200, 200)
         drawBot.save()
         path = drawBot.BezierPath()
         path.rect(5, 5, 10, 10)
         drawBot.clipPath(path)
         drawBot.restore()
         im = drawBot.ImageObject()
         with im:
             drawBot.size(20, 20)
             drawBot.rect(5, 5, 10, 10)
         drawBot.image(im, (10, 10), alpha=.5)
         drawBot.blendMode("saturation")
         drawBot.translate(10, 10)
         drawBot.rect(10, 10, 100, 100)
         drawBot.text("foo bar", (100, 100), align="center")
         drawBot.frameDuration(10)
         drawBot.saveImage("*", myExtraAgrument=True)
         drawBot.endDrawing()
     self.assertEqual(output.lines(), expected)
示例#22
0
 def test_openTypeFeatures_saveRestore(self):
     drawBot.newDrawing()
     drawBot.font("AppleBraille")
     drawBot.save()
     drawBot.restore()
示例#23
0
 def resetShadow(self, e):
     u"""Restore the shadow mode of DrawBot. Should be paired with call self._setShadow()."""
     if e.css('shadowOffset') is not None:
         restore()  # DrawBot graphics state pop.
示例#24
0
 def __exit__(self, type, value, traceback):
     db.restore()
示例#25
0
 def postrenderDrawBot(self):
     ctx.restore()
示例#26
0
    newDrawing()
    newPage(952, 488)

    translate(width() * .27, height() * .25)
    save()
    for eachDisc in range(discs):
        with savedState():
            scale(1, .65)
            hslDonut(rings,
                     ringThickness,
                     holeRadius,
                     fixedValue=eachDisc / (discs - 1),
                     isLuminosityConst=True,
                     captions=False)
        translate(0, 16)
    restore()

    translate(width() * .44, 0)
    save()
    for eachDisc in range(discs):
        with savedState():
            scale(1, .65)
            hslDonut(rings,
                     ringThickness,
                     holeRadius,
                     fixedValue=eachDisc / (discs - 1),
                     isLuminosityConst=True,
                     captions=False)
        translate(0, 16)
    restore()
示例#27
0
 def test_openTypeFeatures_saveRestore(self):
     drawBot.newDrawing()
     drawBot.font("AppleBraille")
     drawBot.save()
     drawBot.restore()
示例#28
0
    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()
示例#29
0
import pathlib
import drawBot
drawBot.size(500, 500)
imagePath = "../data/drawBot.pdf"
w, h = drawBot.imageSize(imagePath)
drawBot.save()
drawBot.scale(250 / w)
drawBot.image(imagePath, (0, 0))
drawBot.restore()

imagePath = "../data/drawBot.png"
w, h = drawBot.imageSize(imagePath)
drawBot.save()
drawBot.scale(250 / w)
drawBot.image(imagePath, (w, 0))
drawBot.restore()

imagePath = "../data/drawBot.jpg"
w, h = drawBot.imageSize(imagePath)
drawBot.save()
drawBot.scale(250 / w)
drawBot.image(imagePath, (0, h))
drawBot.restore()

imagePath = "../data/drawBot.bmp"
w, h = drawBot.imageSize(imagePath)
drawBot.save()
drawBot.scale(250 / w)
drawBot.image(pathlib.Path(imagePath),
              (w, h))  # verify that pathlib.Path objects work
drawBot.restore()
示例#30
0
import drawBot
drawBot.size(200, 200)
drawBot.stroke(0, 0, 1)
drawBot.strokeWidth(5)
drawBot.save()
drawBot.fill(1, 0, 0)
drawBot.translate(100, 100)
drawBot.rect(0, 0, 100, 100)
drawBot.restore()
drawBot.rect(0, 0, 100, 100)
drawBot.save()
drawBot.fill(0, 1, 0)
drawBot.translate(100, 0)
drawBot.rect(0, 0, 100, 100)
drawBot.restore()
drawBot.rect(0, 100, 100, 100)
    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])
示例#32
0
    
    vertical_pigs = math.floor(CANVAS[1] / ((height + margin / 2) * scale))
    horizontal_pigs = math.floor(CANVAS[0] / ((width + margin) * scale))
    
#    for k in range(FRAMES):
        # db.newPage(*CANVAS)
        # db.frameDuration(1/FRAMES)
    db.save()
    db.scale(scale)
    y = -height
    for i in range(vertical_pigs + 2):
        x = -width
        for j in range(horizontal_pigs + 2):
            db.save()
            db.translate(x, y)
            pig = sh.getGlyphPath(ufo_path, random.choice(glyphs))
            # db.fill(j / random.randint(10, 15), i / random.randint(20, 30), random.uniform(0.6, 0.8), 1)
            db.fill(j / 15, i / 20, 0.7, 1)
            db.drawPath(pig)
            db.restore()
            x += width + margin
        y += height
    db.restore()

    db.fill(1)

    db.font('Cooper Std Black', 150)
    db.text('2019', (60, 200))

    db.saveImage('~/Downloads/pig.gif', imageResolution=300)
    db.endDrawing()
示例#33
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()