def drawPoints(self, glyph, scale): save() _onCurveSize = self._onCurvePointsSize * scale _offCurveSize = self._offCurvePointsSize * scale _strokeWidth = self._strokeWidth * scale self._pointsColor.set() path = NSBezierPath.bezierPath() offCurveHandlesPath = NSBezierPath.bezierPath() pointsData = glyph.getRepresentation("doodle.OutlineInformation") for point1, point2 in pointsData["bezierHandles"]: offCurveHandlesPath.moveToPoint_(point1) offCurveHandlesPath.lineToPoint_(point2) for point in pointsData.get("offCurvePoints"): (x, y) = point["point"] path.appendBezierPathWithOvalInRect_(NSMakeRect(x - _offCurveSize, y - _offCurveSize, _offCurveSize * 2, _offCurveSize * 2)) for point in pointsData.get("onCurvePoints"): (x, y) = point["point"] path.appendBezierPathWithRect_(NSMakeRect(x - _onCurveSize, y - _onCurveSize, _onCurveSize * 2, _onCurveSize * 2)) path.fill() offCurveHandlesPath.setLineWidth_(_strokeWidth) strokePixelPath(offCurveHandlesPath) restore()
def drawIcon(foregroundColor, backgroundColor): image = NSImage.alloc().initWithSize_((120, 11)) image.lockFocus() foregroundColor.set() path = NSBezierPath.bezierPath() path.setLineWidth_(1.0) # left path.moveToPoint_((0, 5.5)) path.lineToPoint_((15, 5.5)) path.moveToPoint_((4, 8.5)) path.lineToPoint_((0, 5.5)) path.lineToPoint_((4, 2.5)) # right path.moveToPoint_((120, 5.5)) path.lineToPoint_((105, 5.5)) path.moveToPoint_((114, 8.5)) path.lineToPoint_((120, 5.5)) path.lineToPoint_((114, 2.5)) # center path.moveToPoint_((50, 5.5)) path.lineToPoint_((70, 5.5)) path.moveToPoint_((54, 8.5)) path.lineToPoint_((50, 5.5)) path.lineToPoint_((54, 2.5)) path.moveToPoint_((66, 8.5)) path.lineToPoint_((70, 5.5)) path.lineToPoint_((66, 2.5)) path.stroke() image.unlockFocus() return image
def drawingCalculation(self, curvePoints, interpolFactor): color = self.w.colorFill.get() if len(curvePoints) != 0: path = NSBezierPath.bezierPath() path.setLineWidth_(int(self.w.strokeThickness.get()) / self.scale) for idx, pts in enumerate(curvePoints): if idx == 0: path.moveToPoint_((pts[0],pts[1])) else: path.lineToPoint_((pts[0],pts[1])) color.set() path.stroke() processedPoints = [] interpolatedPoints = [] for i, pts in enumerate(curvePoints): try: pt1 = (pts[0], pts[1]) pt2 = (curvePoints[i+1][0], curvePoints[i+1][1]) processedPoints.append(pt1) processedPoints.append(pt2) interpolatedPt = self.interpolatePoint(pt1, pt2, interpolFactor) interpolatedPoints.append(interpolatedPt) except IndexError: pass return interpolatedPoints return None
def background(self, layer): try: NSColor.colorWithDeviceRed_green_blue_alpha_(0.2, 0.2, 0.2, 0.5).set() for a in layer.anchors: if a not in layer.selection: continue for (l2, otherAnchor) in self.matchingGlyphsAndAnchorsForAnchor( layer, a): if l2.parent.name in self.skipMark: continue anchorAnchorPos = NSPoint( a.position.x - otherAnchor.position.x, a.position.y - otherAnchor.position.y, ) bez = NSBezierPath.bezierPath() bez.appendBezierPath_(l2.bezierPath) t = NSAffineTransform.transform() t.translateXBy_yBy_(anchorAnchorPos.x, anchorAnchorPos.y) bez.transformUsingAffineTransform_(t) bez.fill() except: print("Oops!", sys.exc_info()[0], "occured.") traceback.print_exc(file=sys.stdout)
def drawWithFrame_inView_(self, frame, view): row = view.selectedRow() columnCount = len(view.tableColumns()) frames = [ view.frameOfCellAtColumn_row_(i, row) for i in range(columnCount) ] selected = frame in frames (x, y), (w, h) = frame y += 1 h -= 2 if selected: pillTextAttributes[NSForegroundColorAttributeName] = self._color foregroundColor = NSColor.whiteColor() else: pillTextAttributes[ NSForegroundColorAttributeName] = NSColor.whiteColor() foregroundColor = self._color text = self.title() text = NSAttributedString.alloc().initWithString_attributes_( text, pillTextAttributes) textRect = text.boundingRectWithSize_options_((w, h), 0) (textX, textY), (textW, textH) = textRect foregroundColor.set() path = NSBezierPath.bezierPath() radius = h / 2.0 path.appendBezierPathWithOvalInRect_(((x, y), (h, h))) path.appendBezierPathWithOvalInRect_(((x + textW - 1, y), (h, h))) path.appendBezierPathWithRect_(((x + radius, y), (textW - 1, h))) path.fill() text.drawInRect_(((x + radius, y), (textW, textH)))
def drawHashMarksAndLabelsInRect_(self, rect): bounds = self.bounds() view = self.clientView() rulerBackgroundColor = self.rulerBackgroundColor() if rulerBackgroundColor is not None: rulerBackgroundColor.set() NSRectFill(bounds) if not isinstance(view, NSTextView): return layoutManager = view.layoutManager() container = view.textContainer() text = view.string() nullRange = NSMakeRange(NSNotFound, 0) yinset = view.textContainerInset().height visibleRect = self.scrollView().contentView().bounds() textAttributes = self.textAttributes() lines = self.lineIndices() glyphRange = layoutManager.glyphRangeForBoundingRect_inTextContainer_(visibleRect, container) _range = layoutManager.characterRangeForGlyphRange_actualGlyphRange_(glyphRange, None)[0] _range.length += 1 count = len(lines) index = 0 lineNumber = self.lineNumberForCharacterIndex_inText_(_range.location, text) for line in range(lineNumber, count): index = lines[line] if NSLocationInRange(index, _range): rects, rectCount = layoutManager.rectArrayForCharacterRange_withinSelectedCharacterRange_inTextContainer_rectCount_( NSMakeRange(index, 0), nullRange, container, None ) if rectCount > 0: ypos = yinset + NSMinY(rects[0]) - NSMinY(visibleRect) labelText = NSString.stringWithString_("%s" % (line + 1)) stringSize = labelText.sizeWithAttributes_(textAttributes) x = NSWidth(bounds) - stringSize.width - self.RULER_MARGIN y = ypos + (NSHeight(rects[0]) - stringSize.height) / 2.0 w = NSWidth(bounds) - self.RULER_MARGIN * 2.0 h = NSHeight(rects[0]) labelText.drawInRect_withAttributes_(NSMakeRect(x, y, w, h), textAttributes) if index > NSMaxRange(_range): break path = NSBezierPath.bezierPath() path.moveToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y)) path.lineToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height)) NSColor.grayColor().set() path.stroke()
def _ns_arc_path(self, c, r, sa, ea): ns_path = NSBezierPath.bezierPath() ns_path.setLineWidth_(self._pensize) ns_path.\ appendBezierPathWithArcWithCenter_radius_startAngle_endAngle_( c, r, sa, ea) return ns_path
def drawWithFrame_inView_(self, frame, view): row = view.selectedRow() columnCount = len(view.tableColumns()) frames = [view.frameOfCellAtColumn_row_(i, row) for i in xrange(columnCount)] selected = frame in frames (x, y), (w, h) = frame y += 1 h -= 2 if selected: pillTextAttributes[NSForegroundColorAttributeName] = self._color foregroundColor = NSColor.whiteColor() else: pillTextAttributes[NSForegroundColorAttributeName] = NSColor.whiteColor() foregroundColor = self._color text = self.title() text = NSAttributedString.alloc().initWithString_attributes_(text, pillTextAttributes) textRect = text.boundingRectWithSize_options_((w, h), 0) (textX, textY), (textW, textH) = textRect foregroundColor.set() path = NSBezierPath.bezierPath() radius = h / 2.0 path.appendBezierPathWithOvalInRect_(((x, y), (h, h))) path.appendBezierPathWithOvalInRect_(((x + textW - 1, y), (h, h))) path.appendBezierPathWithRect_(((x + radius, y), (textW - 1, h))) path.fill() text.drawInRect_(((x + radius, y), (textW, textH)))
def __init__(self, glyphSet, path=None): BasePen.__init__(self, glyphSet) if path is None: from AppKit import NSBezierPath path = NSBezierPath.bezierPath() self.path = path
def roundedRectBezierPath(rect, radius, roundUpperLeft=True, roundUpperRight=True, roundLowerLeft=True, roundLowerRight=True, closeTop=True, closeBottom=True, closeLeft=True, closeRight=True): (rectLeft, rectBottom), (rectWidth, rectHeight) = rect rectTop = rectBottom + rectHeight rectRight = rectLeft + rectWidth path = NSBezierPath.bezierPath() if roundUpperLeft: path.moveToPoint_((rectLeft, rectHeight-radius)) path.appendBezierPathWithArcFromPoint_toPoint_radius_((rectLeft, rectTop), (rectLeft+radius, rectTop), radius) else: path.moveToPoint_((rectLeft, rectTop)) if roundUpperRight: if closeTop: path.lineToPoint_((rectRight-radius, rectTop)) else: path.moveToPoint_((rectRight-radius, rectTop)) path.appendBezierPathWithArcFromPoint_toPoint_radius_((rectRight, rectTop), (rectRight, rectTop-radius), radius) else: if closeTop: path.lineToPoint_((rectRight, rectTop)) else: path.moveToPoint_((rectRight, rectTop)) if roundLowerRight: if closeRight: path.lineToPoint_((rectRight, rectBottom+radius)) else: path.moveToPoint_((rectRight, rectBottom+radius)) path.appendBezierPathWithArcFromPoint_toPoint_radius_((rectRight, rectBottom), (rectRight-radius, rectBottom), radius) else: if closeRight: path.lineToPoint_((rectRight, rectBottom)) else: path.moveToPoint_((rectRight, rectBottom)) if roundLowerLeft: if closeBottom: path.lineToPoint_((rectLeft+radius, rectBottom)) else: path.moveToPoint_((rectLeft+radius, rectBottom)) path.appendBezierPathWithArcFromPoint_toPoint_radius_((rectLeft, rectBottom), (rectLeft, rectBottom+radius), radius) else: if closeBottom: path.lineToPoint_((rectLeft, rectBottom)) else: path.moveToPoint_((rectLeft, rectBottom)) if closeLeft: if roundUpperLeft: path.lineToPoint_((rectLeft, rectHeight-radius)) else: path.lineToPoint_((rectLeft, rectTop)) return path
def line(x1, y1, x2=None, y2=None): # draws a line if x2 is None and y2 is None and isinstance(x1, tuple) and isinstance(y1, tuple): (x1, y1), (x2, y2) = x1, y1 p = NSBezierPath.bezierPath() p.moveToPoint_(NSMakePoint(x1, y1)) p.lineToPoint_(NSMakePoint(x2, y2)) drawPath(p)
def drawGlyph(pen, glyph): save() stroke(None) fill(0) pen.path = NSBezierPath.bezierPath() glyph.draw(pen) drawPath(pen.path) restore()
def drawOutline(pen, glyph, color, s): save() strokeWidth(1 / s) stroke(*color) fill(None) pen.path = NSBezierPath.bezierPath() glyph.draw(pen) drawPath(pen.path) restore()
def __init__(self): self._ns_path = NSBezierPath.bezierPath() self._ns_path.setWindingRule_(NSEvenOddWindingRule) self._stack = [] ctx = NSGraphicsContext.currentContext() ctx.setCompositingOperation_(NSCompositeSourceOver) GCanvas.__init__(self) self._printing = not ctx.isDrawingToScreen() self.initgraphics()
def addGlyph(self, glyph): BezierPath = glyph._layer.bezierPath() if BezierPath != None: BezierPath = BezierPath.copy() else: BezierPath = NSBezierPath.bezierPath() for currComponent in glyph._layer.components: BezierPath.appendBezierPath_(currComponent.bezierPath()) self.getNSBezierPath().appendBezierPath_(BezierPath)
def line(x1, y1, x2=None, y2=None): # draws a line if x2 is None and y2 is None and isinstance(x1, tuple) and isinstance( y1, tuple): (x1, y1), (x2, y2) = x1, y1 p = NSBezierPath.bezierPath() p.moveToPoint_(NSMakePoint(x1, y1)) p.lineToPoint_(NSMakePoint(x2, y2)) drawPath(p)
def DrawGlyph(f, glyph, PSCommands, xoffset, yoffset, ratio, fillcolour, strokecolour, strokewidth, dashed): if not PSCommands: layer = glyph.layers[0] p = layer.drawBezierPath transform = NSAffineTransform.new() transform.translateXBy_yBy_(xoffset * mm, yoffset * mm) transform.scaleBy_(ratio) p.transformUsingAffineTransform_(transform) else: p = NSBezierPath.bezierPath() for command in PSCommands: if command[0] == 'moveTo': try: p.close() except: pass x = xoffset * mm + command[1][0] * ratio y = yoffset * mm + command[1][1] * ratio p.moveToPoint_((x, y)) #print "('moveTo', (%s, %s))," % (command[1][0], command[1][1]) if command[0] == 'lineTo': x = xoffset * mm + command[1][0] * ratio y = yoffset * mm + command[1][1] * ratio p.lineToPoint_((x, y)) #print "('lineTo', (%s, %s))," % (command[1][0], command[1][1]) if command[0] == 'curveTo': points = [] for point in command[1:]: points.append((xoffset * mm + point[0] * ratio, yoffset * mm + point[1] * ratio)) p.curveToPoint_controlPoint1_controlPoint2_( points[0], points[1], points[2]) p.closePath() if fillcolour: NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_( fillcolour[0], fillcolour[1], fillcolour[2], fillcolour[3], 1).set() p.fill() if strokecolour: NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_( strokecolour[0], strokecolour[1], strokecolour[2], strokecolour[3], 1).set() if dashed: p.setLineDash_count_phase_(dashed, 2, 0.0) p.setLineWidth_(strokewidth) p.stroke()
def drawRect_(self, rect): try: NSColor.whiteColor().set() NSRectFill(self.bounds()) NSColor.blackColor().setFill() NSColor.blueColor().setStroke() p = NSBezierPath.bezierPath() xcursor = 0 string = self.string master = self.master for s in range(0, len(string)): thisPath = NSBezierPath.bezierPath() gsglyph = master.font.glyphs[string[s]] layer = gsglyph.layers[master.id] thisPath.appendBezierPath_(layer.completeBezierPath) # print("X cursor was",xcursor) xcursor = xcursor - layer.bounds.origin.x # print("Moving backwards", layer.bounds.origin.x) t = NSAffineTransform.transform() t.translateXBy_yBy_(xcursor, -master.descender) thisPath.transformUsingAffineTransform_(t) # print("Drawing at",xcursor) # print(thisPath) xcursor = xcursor + layer.bounds.origin.x xcursor = xcursor + layer.bounds.size.width # print("Adding width", layer.bounds.size.width) if s < len(string) - 1: xcursor = xcursor + self.distances[(string[s], string[s + 1])] p.appendBezierPath_(thisPath) t = NSAffineTransform.transform() if xcursor > 0: vscale = self.bounds().size.height / (master.ascender - master.descender) hscale = self.bounds().size.width / xcursor t.scaleBy_(min(hscale, vscale)) p.transformUsingAffineTransform_(t) p.fill() except: print("Oops!", sys.exc_info()[0], "occured.") traceback.print_exc(file=sys.stdout)
def drawLine(self, x1, y1, x2, y2, strokeWidth=1): try: myPath = NSBezierPath.bezierPath() myPath.moveToPoint_( (x1, y1) ) myPath.lineToPoint_( (x2, y2) ) myPath.setLineWidth_( strokeWidth/self.getScale() ) selectionColor = 0, 0, 0.5, 0.2 NSColor.colorWithCalibratedRed_green_blue_alpha_( *selectionColor ).set() myPath.stroke() except: print(traceback.format_exc())
def drawline(x1, y1, x2, y2, colour, strokewidth, dashed): NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(colour[0], colour[1], colour[2], colour[3], 1).set() Path = NSBezierPath.bezierPath() Path.moveToPoint_((x1, y1)) Path.lineToPoint_((x2, y2)) Path.setLineWidth_(strokewidth) if dashed: Path.setLineDash_count_phase_(dashed, 2, 0.0) Path.stroke()
def draw_bbox(x1, y1, x2, y2, x3, y3, x4, y4, outline=False): path = NSBezierPath.bezierPath() path.moveToPoint_((x1, y1)) path.lineToPoint_((x2, y2)) path.lineToPoint_((x3, y3)) path.lineToPoint_((x4, y4)) path.lineToPoint_((x1, y1)) if not outline: path.fill() else: path.setLineWidth_(30) path.stroke()
def drawGlyph(glyph): BezierPath = glyph._layer.bezierPath if BezierPath != None: BezierPath = BezierPath.copy() else: BezierPath = NSBezierPath.bezierPath() OpenBezierPath = glyph._layer.openBezierPath if OpenBezierPath: BezierPath.appendBezierPath_(OpenBezierPath) for currComponent in glyph._layer.components: BezierPath.appendBezierPath_(currComponent.bezierPath) _drawBotDrawingTool.drawPath(BezierPath)
def drawGlyph(glyph): BezierPath = glyph._layer.bezierPath() if BezierPath != None: BezierPath = BezierPath.copy() else: BezierPath = NSBezierPath.bezierPath() OpenBezierPath = glyph._layer.openBezierPath() if OpenBezierPath: BezierPath.appendBezierPath_(OpenBezierPath) for currComponent in glyph._layer.components: BezierPath.appendBezierPath_(currComponent.bezierPath()) _drawBotDrawingTool.drawPath(BezierPath)
def drawline(x1, y1, x2, y2, colour, strokewidth, dashed): NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_( colour[0], colour[1], colour[2], colour[3], 1).set() Path = NSBezierPath.bezierPath() Path.moveToPoint_((x1, y1)) Path.lineToPoint_((x2, y2)) Path.setLineWidth_(strokewidth) if dashed: Path.setLineDash_count_phase_(dashed, 2, 0.0) Path.stroke()
def drawCellHorizontalMetrics(self, rect): (xMin, yMin), (width, height) = rect font = self.font scale = self.scale yOffset = self.yOffset path = NSBezierPath.bezierPath() lines = set((0, font.info.descender, font.info.xHeight, font.info.capHeight, font.info.ascender)) for y in lines: y = round((y * scale) + yMin + yOffset) - .5 path.moveToPoint_((xMin, y)) path.lineToPoint_((xMin + width, y)) cellMetricsLineColor.set() path.setLineWidth_(1.0) path.stroke()
def drawHistogram(self, originX, originY, width, height): NSColor.colorWithWhite_alpha_(0, .5).set() path = NSBezierPath.bezierPath() path.moveToPoint_((originX, originY - 2)) prevY = 0 for x in range(width): if x in self.histogram: y = (self.histogram[x] / float(self.maxhistogram)) * height path.lineToPoint_((x + .5 + originX, y + originY)) else: path.lineToPoint_((x + .5 + originX, originY - 2)) path.lineToPoint_((originX + width, originY - 2)) path.closePath() path.fill()
def DrawGlyph(f, glyph, PSCommands, xoffset, yoffset, ratio, fillcolour, strokecolour, strokewidth, dashed): if not PSCommands: layer = glyph.layers[0] p = layer.drawBezierPath transform = NSAffineTransform.new() transform.translateXBy_yBy_(xoffset*mm, yoffset*mm) transform.scaleBy_(ratio) p.transformUsingAffineTransform_(transform) else: p = NSBezierPath.bezierPath() for command in PSCommands: if command[0] == 'moveTo': try: p.close() except: pass x = xoffset*mm + command[1][0] * ratio y = yoffset*mm + command[1][1] * ratio p.moveToPoint_((x, y)) #print "('moveTo', (%s, %s))," % (command[1][0], command[1][1]) if command[0] == 'lineTo': x = xoffset*mm + command[1][0] * ratio y = yoffset*mm + command[1][1] * ratio p.lineToPoint_((x, y)) #print "('lineTo', (%s, %s))," % (command[1][0], command[1][1]) if command[0] == 'curveTo': points = [] for point in command[1:]: points.append( (xoffset*mm + point[0] * ratio, yoffset*mm + point[1] * ratio) ) p.curveToPoint_controlPoint1_controlPoint2_(points[0], points[1], points[2]) p.closePath() if fillcolour: NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(fillcolour[0], fillcolour[1], fillcolour[2], fillcolour[3], 1).set() p.fill() if strokecolour: NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(strokecolour[0], strokecolour[1], strokecolour[2], strokecolour[3], 1).set() if dashed: p.setLineDash_count_phase_(dashed, 2, 0.0) p.setLineWidth_(strokewidth) p.stroke()
def getGraph(self): path = NSBezierPath.bezierPath() maxMag = 0 mag = self.fieldValue(0) maxMag = max(maxMag, mag) path.moveToPoint_(polarToRect((mag, 0))) for deg in range(1, 359, 1): r = (deg / 180.0) * pi mag = self.fieldValue(r) maxMag = max(maxMag, mag) path.lineToPoint_(polarToRect((mag, r))) path.closePath() return path, maxMag
def getGraph(self): path = NSBezierPath.bezierPath() maxMag = 0 mag = self.fieldValue(0) maxMag = max(maxMag, mag) path.moveToPoint_(polarToRect((mag, 0))) for deg in range(1, 359, 1): r = (deg/180.0)*pi mag = self.fieldValue(r) maxMag = max(maxMag, mag) path.lineToPoint_(polarToRect((mag, r))) path.closePath() return path, maxMag;
def drawCellHeaderBackground(self, rect): (xMin, yMin), (width, height) = rect # background try: gradient = NSGradient.alloc().initWithColors_([cellHeaderHighlightColor, cellHeaderBaseColor]) gradient.drawInRect_angle_(rect, 90) except NameError: cellHeaderBaseColor.set() NSRectFill(rect) # bottom line cellHeaderLineColor.set() bottomPath = NSBezierPath.bezierPath() bottomPath.moveToPoint_((xMin, yMin + height - .5)) bottomPath.lineToPoint_((xMin + width, yMin + height - .5)) bottomPath.setLineWidth_(1.0) bottomPath.stroke()
def _DrawCurvatureIllustration(self): # Recalc illustration prefIllustrationPositionIndex = int( self.segment.speedpunklib.illustrationPositionIndex) prefCurveGain = self.segment.speedpunklib.curveGain if self.segment.speedpunklib.glyphchanged or self.curveGain != prefCurveGain or self.illustrationPosition != prefIllustrationPositionIndex: #print("__illustration") self.curveGain = prefCurveGain self.illustrationPosition = prefIllustrationPositionIndex k1 = self.set1[ 3] * drawfactor * self.curveGain * self.segment.speedpunklib.unitsperem**2 k2 = self.set2[ 3] * drawfactor * self.curveGain * self.segment.speedpunklib.unitsperem**2 if self.illustrationPosition == outsideOfGlyph: k1 = abs(k1) k2 = abs(k2) # TrueType if self.segment.speedpunklib.curves == 'quadratic': k1 *= -1 k2 *= -1 # Define points S10 = self.set1[0] S11 = self.set1[1] S20 = self.set2[0] S21 = self.set2[1] self.oncurve1 = S10 self.oncurve2 = S20 S21abs = math.sqrt(S21.x**2 + S21.y**2) S11abs = math.sqrt(S11.x**2 + S11.y**2) self.outerspace2 = (S20.x + (S21.y / S21abs * k2), S20.y - (S21.x / S21abs * k2)) self.outerspace1 = (S10.x + (S11.y / S11abs * k1), S10.y - (S11.x / S11abs * k1)) self.path = NSBezierPath.bezierPath() # OnCurve self.path.moveToPoint_(self.oncurve1) self.path.lineToPoint_(self.oncurve2) # Outer points self.path.lineToPoint_(self.outerspace2) self.path.lineToPoint_(self.outerspace1) self.path.closePath()
def drawCellHeaderBackground(self, rect): (xMin, yMin), (width, height) = rect # background try: gradient = NSGradient.alloc().initWithColors_( [cellHeaderHighlightColor, cellHeaderBaseColor]) gradient.drawInRect_angle_(rect, 90) except NameError: cellHeaderBaseColor.set() NSRectFill(rect) # bottom line cellHeaderLineColor.set() bottomPath = NSBezierPath.bezierPath() bottomPath.moveToPoint_((xMin, yMin + height - .5)) bottomPath.lineToPoint_((xMin + width, yMin + height - .5)) bottomPath.setLineWidth_(1.0) bottomPath.stroke()
def drawingCalculation(self, glyph, listOfSelectedPoints, interpolFactor): color = self.w.colorFill.get() if len(listOfSelectedPoints) != 0: path = NSBezierPath.bezierPath() path.setLineWidth_(int(self.w.strokeThickness.get())) for idx, pts in enumerate(listOfSelectedPoints): if idx == 0: (startpoint_x, startpoint_y) = (listOfSelectedPoints[0][0], listOfSelectedPoints[0][1]) path.moveToPoint_((startpoint_x, startpoint_y)) else: path.lineToPoint_(((pts[0]), (pts[1]))) color.set() path.stroke() processedPoints = [] interpolatedPoints = [] for i, pts in enumerate(listOfSelectedPoints): try: pt1 = (listOfSelectedPoints[i][0], listOfSelectedPoints[i][1]) pt2 = (listOfSelectedPoints[i + 1][0], listOfSelectedPoints[i + 1][1]) processedPoints.append(pt1) processedPoints.append(pt2) interpolatedPt = self.interpolatePoint( pt1, pt2, interpolFactor) interpolatedPoints.append(interpolatedPt) if interpolatedPt in processedPoints: pass else: pass except IndexError: pass self.interpolatedPoints = interpolatedPoints
def drawLine(xy1, xy2, lineWidth=1.0): x1, y1 = xy1 x2, y2 = xy2 turnOffAntiAliasing = False if x1 == x2 or y1 == y2: turnOffAntiAliasing = True if turnOffAntiAliasing: context = NSGraphicsContext.currentContext() context.setShouldAntialias_(False) path = NSBezierPath.bezierPath() path.moveToPoint_((x1, y1)) path.lineToPoint_((x2, y2)) if turnOffAntiAliasing and lineWidth == 1.0: lineWidth = 0.001 path.setLineWidth_(lineWidth) path.stroke() if turnOffAntiAliasing: context.setShouldAntialias_(True)
def drawSegment_inFrame_withView_(self, segment, frame, view): (x, y), (w, h) = frame # draw highlight if self.isSelectedForSegment_(segment): NSColor.colorWithCalibratedWhite_alpha_(0, .2).set() NSRectFillUsingOperation(frame, NSCompositeSourceOver) # draw border if segment != 0: path = NSBezierPath.bezierPath() path.moveToPoint_((x + .5, y + h)) path.lineToPoint_((x + .5, y)) path.setLineWidth_(1.0) placardBorderColor.set() path.stroke() x += 1 # draw image image = self.imageForSegment_(segment) if image is not None: image.drawAtPoint_fromRect_operation_fraction_((x, y), ((0, 0), image.size()), NSCompositeSourceOver, 1.0)
def drawGradientImage(self): width = int( self.prefwindow.w.gradientImage.getNSImageView().frame().size[0]) height = int( self.prefwindow.w.gradientImage.getNSImageView().frame().size[1]) image = NSImage.alloc().initWithSize_((width, height)) image.lockFocus() for x in range(width): p = x / float(width) R, G, B = InterpolateHexColorList(colors[self.curves], p) NSColor.colorWithCalibratedRed_green_blue_alpha_(R, G, B, 1.0).set() path = NSBezierPath.bezierPath() path.moveToPoint_((x, 0)) path.lineToPoint_((x, height)) path.stroke() image.unlockFocus() self.prefwindow.w.gradientImage.setImage(imageObject=image)
def drawBorderAndBackgroundWithFrame_inView_(self, frame, view): # draw background try: gradient = NSGradient.alloc().initWithColors_([placardGradientColor1, placardGradientColor2]) gradient.drawInRect_angle_(frame, 90) except NameError: placardGradientColorFallback.set() NSRectFill(frame) # draw border (x, y), (w, h) = frame path = NSBezierPath.bezierPath() path.moveToPoint_((x + w - .5, h)) path.lineToPoint_((x + w - .5, .5)) path.lineToPoint_((x, .5)) path.setLineWidth_(1.0) NSColor.colorWithCalibratedWhite_alpha_(.5, .7).set() path.stroke() # let the super do the rest w -= 1 if inOS104: w -= 4 frame = ((x, y), (w, h)) super(DefconAppKitPlacardNSPopUpButtonCell, self).drawBorderAndBackgroundWithFrame_inView_(frame, view)
def drawDot(self, point, colorDots): widthP = int(self.w.ptThickness.get()) path = NSBezierPath.bezierPath() path.moveToPoint_((point[0] - widthP, point[1] + 0)) path.curveToPoint_controlPoint1_controlPoint2_( (point[0] + 0, point[1] + widthP), (point[0] - widthP, point[1] + widthP), (point[0] + 0, point[1] + widthP)) path.curveToPoint_controlPoint1_controlPoint2_( (point[0] + widthP, point[1] + 0), (point[0] + widthP, point[1] + widthP), (point[0] + widthP, point[1] + 0)) path.curveToPoint_controlPoint1_controlPoint2_( (point[0] + 0, point[1] - widthP), (point[0] + widthP, point[1] - widthP), (point[0] + 0, point[1] - widthP)) path.curveToPoint_controlPoint1_controlPoint2_( (point[0] - widthP, point[1] + 0), (point[0] - widthP, point[1] - widthP), (point[0] - widthP, point[1] + 0)) path.closePath() colorDots.set() path.fill()
def drawHistogram(self): width = int( self.prefwindow.w.histogramImage.getNSImageView().frame().size[0]) height = int( self.prefwindow.w.histogramImage.getNSImageView().frame().size[1]) image = NSImage.alloc().initWithSize_((width, height)) image.lockFocus() image.setBackgroundColor_( NSColor.colorWithCalibratedRed_green_blue_alpha_(1, 1, 1, 0)) NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 0, .8).set() for x in range(width): if x in self.histogram: path = NSBezierPath.bezierPath() path.moveToPoint_((x + .5, 0)) y = (self.histogram[x] / float(self.maxhistogram)) * height path.lineToPoint_((x + .5, y)) path.stroke() image.unlockFocus() self.prefwindow.w.histogramImage.setImage(imageObject=image)
def drawWithFrame_inView_(self, frame, view): # draw background try: gradient = NSGradient.alloc().initWithColors_([placardGradientColor1, placardGradientColor2]) gradient.drawInRect_angle_(frame, 90) except NameError: placardGradientColorFallback.set() NSRectFill(frame) # draw border (x, y), (w, h) = frame path = NSBezierPath.bezierPath() path.moveToPoint_((x + w - .5, h)) path.lineToPoint_((x + w - .5, .5)) path.lineToPoint_((x, .5)) path.setLineWidth_(1.0) placardBorderColor.set() path.stroke() # draw segments x, y = frame.origin h = frame.size[1] for index in xrange(self.segmentCount()): w = self.widthForSegment_(index) self.drawSegment_inFrame_withView_(index, ((x, y), (w, h)), view) x += w
def newPath(): # creates a new path currentPath = NSBezierPath.bezierPath()
def drawGlyphPoints(glyph, scale, rect, drawStartPoint=True, drawOnCurves=True, drawOffCurves=True, drawCoordinates=True, color=None, backgroundColor=None, flipped=False): layer = glyph.layer if layer is not None: if layer.color is not None: color = colorToNSColor(layer.color) if color is None: color = getDefaultColor("glyphPoints") if backgroundColor is None: backgroundColor = getDefaultColor("background") # get the outline data outlineData = glyph.getRepresentation("defconAppKit.OutlineInformation") points = [] # start point if drawStartPoint and outlineData["startPoints"]: startWidth = startHeight = 15 * scale startHalf = startWidth / 2.0 path = NSBezierPath.bezierPath() for point, angle in outlineData["startPoints"]: x, y = point if angle is not None: path.moveToPoint_((x, y)) path.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle_clockwise_( (x, y), startHalf, angle - 90, angle + 90, True) path.closePath() else: path.appendBezierPathWithOvalInRect_(((x - startHalf, y - startHalf), (startWidth, startHeight))) r = color.redComponent() g = color.greenComponent() b = color.blueComponent() a = color.alphaComponent() a *= 0.3 startPointColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(r, g, b, a) startPointColor.set() path.fill() # off curve if drawOffCurves and outlineData["offCurvePoints"]: # lines color.set() for point1, point2 in outlineData["bezierHandles"]: drawLine(point1, point2) # points offWidth = 3 * scale offHalf = offWidth / 2.0 path = NSBezierPath.bezierPath() for point in outlineData["offCurvePoints"]: x, y = point["point"] points.append((x, y)) x -= offHalf y -= offHalf path.appendBezierPathWithOvalInRect_(((x, y), (offWidth, offWidth))) path.setLineWidth_(3.0 * scale) color.set() path.stroke() backgroundColor.set() path.fill() color.set() path.setLineWidth_(1.0 * scale) # on curve if drawOnCurves and outlineData["onCurvePoints"]: width = 4 * scale half = width / 2.0 smoothWidth = 5 * scale smoothHalf = smoothWidth / 2.0 path = NSBezierPath.bezierPath() for point in outlineData["onCurvePoints"]: x, y = point["point"] points.append((x, y)) if point["smooth"]: x -= smoothHalf y -= smoothHalf path.appendBezierPathWithOvalInRect_(((x, y), (smoothWidth, smoothWidth))) else: x -= half y -= half path.appendBezierPathWithRect_(((x, y), (width, width))) backgroundColor.set() path.setLineWidth_(3.0 * scale) path.stroke() color.set() path.fill() # coordinates if drawCoordinates: r = color.redComponent() g = color.greenComponent() b = color.blueComponent() a = color.alphaComponent() a *= 0.6 color = NSColor.colorWithCalibratedRed_green_blue_alpha_(r, g, b, a) fontSize = 9 attributes = { NSFontAttributeName: NSFont.systemFontOfSize_(fontSize), NSForegroundColorAttributeName: color } for x, y in points: posX = x posY = y - 3 x = round(x, 1) if int(x) == x: x = int(x) y = round(y, 1) if int(y) == y: y = int(y) text = "%d %d" % (x, y) drawTextAtPoint(text, (posX, posY), scale, attributes=attributes, xAlign="center", yAlign="top", flipped=flipped)
def drawFilledOval(rect): path = NSBezierPath.bezierPath() path.appendBezierPathWithOvalInRect_(rect) path.fill()
def GlyphCellDetailFactory(glyph): font = glyph.font imageWidth = 200 imageHeight = 280 scale = 120 / font.info.unitsPerEm glyphLeftOffset = (imageWidth - (glyph.width * scale)) / 2 basePath = roundedRectBezierPath(((.5, .5), (imageWidth - 1, imageHeight - 1)), 7) basePath.setLineWidth_(1.0) glyphPath = glyph.getRepresentation("defconAppKit.NSBezierPath") line1Path = NSBezierPath.bezierPath() line1Path.moveToPoint_((1, 120.5)) line1Path.lineToPoint_((imageWidth - 1, 120.5)) line1Path.setLineWidth_(1.0) line2Path = NSBezierPath.bezierPath() line2Path.moveToPoint_((1, 121.5)) line2Path.lineToPoint_((imageWidth - 1, 121.5)) line2Path.setLineWidth_(1.0) lineColor = NSColor.colorWithCalibratedWhite_alpha_(.5, 1.0) paragraph = NSMutableParagraphStyle.alloc().init() paragraph.setAlignment_(NSRightTextAlignment) paragraph.setLineBreakMode_(NSLineBreakByCharWrapping) leftAttributes = { NSFontAttributeName: NSFont.systemFontOfSize_(12.0), NSForegroundColorAttributeName: NSColor.whiteColor(), NSParagraphStyleAttributeName: paragraph } paragraph = NSMutableParagraphStyle.alloc().init() paragraph.setAlignment_(NSLeftTextAlignment) paragraph.setLineBreakMode_(NSLineBreakByTruncatingMiddle) rightAttributes = { NSFontAttributeName: NSFont.systemFontOfSize_(12.0), NSForegroundColorAttributeName: NSColor.whiteColor(), NSParagraphStyleAttributeName: paragraph } nameTitle = NSAttributedString.alloc().initWithString_attributes_("Name", leftAttributes) nameText = NSAttributedString.alloc().initWithString_attributes_(glyph.name, rightAttributes) uniTitle = NSAttributedString.alloc().initWithString_attributes_("Unicode", leftAttributes) uni = glyph.unicode if uni is None: uni = "" else: uni = hex(uni)[2:].upper() if len(uni) < 4: uni = uni.zfill(4) uniText = NSAttributedString.alloc().initWithString_attributes_(str(uni), rightAttributes) widthTitle = NSAttributedString.alloc().initWithString_attributes_("Width", leftAttributes) width = glyph.width if width is None: width = 0 width = round(width, 3) if width == int(width): width = int(width) widthText = NSAttributedString.alloc().initWithString_attributes_(str(width), rightAttributes) leftTitle = NSAttributedString.alloc().initWithString_attributes_("Left Margin", leftAttributes) leftMargin = glyph.leftMargin if leftMargin is None: leftMargin = 0 leftMargin = round(leftMargin, 3) if leftMargin == int(leftMargin): leftMargin = int(leftMargin) leftText = NSAttributedString.alloc().initWithString_attributes_(str(leftMargin), rightAttributes) rightTitle = NSAttributedString.alloc().initWithString_attributes_("Right Margin", leftAttributes) rightMargin = glyph.rightMargin if rightMargin is None: rightMargin = 0 rightMargin = round(rightMargin, 3) if rightMargin == int(rightMargin): rightMargin = int(rightMargin) rightText = NSAttributedString.alloc().initWithString_attributes_(str(rightMargin), rightAttributes) image = NSImage.alloc().initWithSize_((imageWidth, imageHeight)) image.setFlipped_(True) image.lockFocus() NSColor.colorWithCalibratedWhite_alpha_(0, .65).set() basePath.fill() lineColor.set() basePath.stroke() context = NSGraphicsContext.currentContext() context.saveGraphicsState() transform = NSAffineTransform.transform() transform.translateXBy_yBy_(glyphLeftOffset, 145) transform.scaleBy_(scale) transform.translateXBy_yBy_(0, -font.info.descender) transform.concat() NSColor.whiteColor().set() glyphPath.fill() context.restoreGraphicsState() lineColor.set() line1Path.stroke() NSColor.colorWithCalibratedWhite_alpha_(0, .5).set() line2Path.stroke() transform = NSAffineTransform.transform() transform.translateXBy_yBy_(0, 110) transform.scaleXBy_yBy_(1.0, -1.0) transform.concat() nameTitle.drawInRect_(((0, 0), (90, 17))) nameText.drawInRect_(((95, 0), (85, 17))) uniTitle.drawInRect_(((0, 20), (90, 17))) uniText.drawInRect_(((95, 20), (85, 17))) widthTitle.drawInRect_(((0, 40), (90, 17))) widthText.drawInRect_(((95, 40), (85, 17))) leftTitle.drawInRect_(((0, 60), (90, 17))) leftText.drawInRect_(((95, 60), (85, 17))) rightTitle.drawInRect_(((0, 80), (90, 17))) rightText.drawInRect_(((95, 80), (85, 17))) image.unlockFocus() return image
def rounded(img, radius): img.clip = NSBezierPath.bezierPath() img.clip.appendBezierPathWithRoundedRect_xRadius_yRadius_(img.rect(), radius, radius) return img
p2 = NSBezierPath.bezierPathWithOvalInRect_(((40, 40), (100, 100))) # Outside of bounding box p3 = NSBezierPath.bezierPathWithOvalInRect_(((110, 0), (100, 100))) # In bounding box, doesn't intersect p4 = NSBezierPath.bezierPathWithOvalInRect_(((72, 72), (100, 100))) from cPolymagic import * print intersects(p1, p4) f = NSFont.fontWithName_size_("Helvetica", 72) fp1 = NSBezierPath.bezierPath() fp1.moveToPoint_((100, 100)) fp1.appendBezierPathWithGlyph_inFont_(68, f) fp2 = NSBezierPath.bezierPath() fp2.moveToPoint_((110, 100)) fp2.appendBezierPathWithGlyph_inFont_(68, f) print intersects(fp1, fp2) # Some other thing inside of the function perhaps? print intersects(fp2, fp2) p = union(fp1, fp2) print p.elementCount()
def drawFilledOval(rect): path = NSBezierPath.bezierPath() path.appendBezierPathWithOvalInRect_(rect) path.fill() def drawLine((x1, y1), (x2, y2), lineWidth=1.0): turnOffAntiAliasing = False if x1 == x2 or y1 == y2: turnOffAntiAliasing = True if turnOffAntiAliasing: context = NSGraphicsContext.currentContext() context.setShouldAntialias_(False) path = NSBezierPath.bezierPath() path.moveToPoint_((x1, y1)) path.lineToPoint_((x2, y2)) if turnOffAntiAliasing and lineWidth == 1.0: lineWidth = 0.001 path.setLineWidth_(lineWidth) path.stroke() if turnOffAntiAliasing: context.setShouldAntialias_(True) def drawTextAtPoint(text, pt, scale, attributes={}, xAlign="left", yAlign="bottom", flipped=False): text = NSAttributedString.alloc().initWithString_attributes_(text, attributes) if xAlign != "left" or yAlign != "bottom": width, height = text.size() width *= scale