def transform(shiftX=0.0, shiftY=0.0, rotate=0.0, skew=0.0, scale=1.0): """ Returns an NSAffineTransform object for transforming layers. Apply an NSAffineTransform t object like this: Layer.transform_checkForSelection_doComponents_(t,False,True) Access its transformation matrix like this: tMatrix = t.transformStruct() # returns the 6-float tuple Apply the matrix tuple like this: Layer.applyTransform(tMatrix) Component.applyTransform(tMatrix) Path.applyTransform(tMatrix) Chain multiple NSAffineTransform objects t1, t2 like this: t1.appendTransform_(t2) """ myTransform = NSAffineTransform.transform() if rotate: myTransform.rotateByDegrees_(rotate) if scale != 1.0: myTransform.scaleBy_(scale) if not (shiftX == 0.0 and shiftY == 0.0): myTransform.translateXBy_yBy_(shiftX, shiftY) if skew: skewStruct = NSAffineTransformStruct() skewStruct.m11 = 1.0 skewStruct.m22 = 1.0 skewStruct.m21 = math.tan(math.radians(skew)) skewTransform = NSAffineTransform.transform() skewTransform.setTransformStruct_(skewStruct) myTransform.appendTransform_(skewTransform) return myTransform
def drawRect_(self, rect): NSColor.whiteColor().set() NSBezierPath.fillRect_(rect) if Glyphs.font is None: return if not Glyphs.font.selectedLayers: return glyphToRotate = None try: glyphToRotate = Glyphs.font.selectedLayers[0] except: print(traceback.format_exc()) if glyphToRotate is None: return try: previewPath = glyphToRotate.completeBezierPath rotationFactor = self.wrapper._rotationFactor Width = NSWidth(self.frame()) Height = NSHeight(self.frame()) scaleFactor = 0.666666 / (glyphToRotate.parent.parent.upm / min(Width, Height)) ## scaling and zeroing the glyph #------------------------ transform = NSAffineTransform.transform() transform.scaleBy_(scaleFactor) bounds = glyphToRotate.bounds transform.translateXBy_yBy_(-NSMidX(bounds), -NSMidY(bounds)) previewPath.transformUsingAffineTransform_(transform) ## rotation #------------------------ transform = NSAffineTransform.transform() transform.rotateByDegrees_(rotationFactor) previewPath.transformUsingAffineTransform_(transform) ## positioning to the middle of the viewport #------------------------ transform = NSAffineTransform.transform() transform.translateXBy_yBy_(Width / 2, Height / 2 - 8) previewPath.transformUsingAffineTransform_(transform) ## fill path #------------------------ NSColor.blackColor().set() previewPath.fill() except: print(traceback.format_exc())
def getImage(self): image = NSImage.alloc().initWithSize_((self.width, self.height)) image.setFlipped_(True) image.lockFocus() context = NSGraphicsContext.currentContext() bodyRect = ((0, 0), (self.width, self.height - self.headerHeight)) headerRect = ((0, -self.height + self.headerHeight), (self.width, self.headerHeight)) # draw a background color cellBackgroundColor.set() NSRectFill(((0, 0), (self.width, self.height))) # background context.saveGraphicsState() bodyTransform = NSAffineTransform.transform() bodyTransform.translateXBy_yBy_(0, self.height - self.headerHeight) bodyTransform.scaleXBy_yBy_(1.0, -1.0) bodyTransform.concat() self.drawCellBackground(bodyRect) context.restoreGraphicsState() # glyph if self.shouldDrawMetrics: self.drawCellHorizontalMetrics(bodyRect) self.drawCellVerticalMetrics(bodyRect) context.saveGraphicsState() NSBezierPath.clipRect_( ((0, 0), (self.width, self.height - self.headerHeight))) glyphTransform = NSAffineTransform.transform() glyphTransform.translateXBy_yBy_(self.xOffset, self.yOffset) glyphTransform.scaleBy_(self.scale) glyphTransform.concat() self.drawCellGlyph() context.restoreGraphicsState() # foreground context.saveGraphicsState() bodyTransform.concat() self.drawCellForeground(bodyRect) context.restoreGraphicsState() # header if self.shouldDrawHeader: context.saveGraphicsState() headerTransform = NSAffineTransform.transform() headerTransform.translateXBy_yBy_(0, self.headerHeight) headerTransform.scaleXBy_yBy_(1.0, -1.0) headerTransform.concat() self.drawCellHeaderBackground(headerRect) self.drawCellHeaderText(headerRect) context.restoreGraphicsState() # done image.unlockFocus() return image
def getImage(self): image = NSImage.alloc().initWithSize_((self.width, self.height)) image.setFlipped_(True) image.lockFocus() context = NSGraphicsContext.currentContext() bodyRect = ((0, 0), (self.width, self.height - self.headerHeight)) headerRect = ((0, -self.height + self.headerHeight), (self.width, self.headerHeight)) # draw a background color cellBackgroundColor.set() NSRectFill(((0, 0), (self.width, self.height))) # background context.saveGraphicsState() bodyTransform = NSAffineTransform.transform() bodyTransform.translateXBy_yBy_(0, self.height - self.headerHeight) bodyTransform.scaleXBy_yBy_(1.0, -1.0) bodyTransform.concat() self.drawCellBackground(bodyRect) context.restoreGraphicsState() # glyph if self.shouldDrawMetrics: self.drawCellHorizontalMetrics(bodyRect) self.drawCellVerticalMetrics(bodyRect) context.saveGraphicsState() NSBezierPath.clipRect_(((0, 0), (self.width, self.height - self.headerHeight))) glyphTransform = NSAffineTransform.transform() glyphTransform.translateXBy_yBy_(self.xOffset, self.yOffset) glyphTransform.scaleBy_(self.scale) glyphTransform.concat() self.drawCellGlyph() context.restoreGraphicsState() # foreground context.saveGraphicsState() bodyTransform.concat() self.drawCellForeground(bodyRect) context.restoreGraphicsState() # header if self.shouldDrawHeader: context.saveGraphicsState() headerTransform = NSAffineTransform.transform() headerTransform.translateXBy_yBy_(0, self.headerHeight) headerTransform.scaleXBy_yBy_(1.0, -1.0) headerTransform.concat() self.drawCellHeaderBackground(headerRect) self.drawCellHeaderText(headerRect) context.restoreGraphicsState() # done image.unlockFocus() return image
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 height *= scale x, y = pt f = 1 if flipped: f = -1 if xAlign == "center": x -= width / 2 elif xAlign == "right": x -= width if yAlign == "center": y -= height / 2 * f elif yAlign == "top": y -= height * f pt = (x, y) context = NSGraphicsContext.currentContext() context.saveGraphicsState() transform = NSAffineTransform.transform() transform.translateXBy_yBy_(pt[0], pt[1]) if flipped: s = -scale else: s = scale transform.scaleXBy_yBy_(scale, s) transform.concat() text.drawAtPoint_((0, 0)) context.restoreGraphicsState()
def _drawUnspecified(self, position, kind, size, vector=(-1, 1)): if vector is None: vector = (-1, 1) angle = atan2(vector[1], vector[0]) circle_size = size * 1.3 x, y = position NSColor.colorWithCalibratedRed_green_blue_alpha_(0.9, 0.1, 0.0, 0.85).set() t = NSAffineTransform.transform() t.translateXBy_yBy_(x, y) t.rotateByRadians_(angle) myPath = NSBezierPath.alloc().init() myPath.setLineWidth_(0) myPath.appendBezierPathWithOvalInRect_( NSMakeRect(x - 0.5 * circle_size, y - 0.5 * circle_size, circle_size, circle_size)) myPath.stroke() if self.show_labels or distance_between_points(self.mouse_position, position) < size: self._drawTextLabel( transform=t, text=kind, size=size, angle=angle, )
def __init__(self, width, height): GPixmap.__init__(self) # ns_size = NSSize(width, height) # ns_image = NSImage.alloc().initWithSize_(ns_size) ns_image = NSImage.alloc().init() ns_image.setCacheMode_(NSImageCacheNever) row_bytes = 4 * width ns_bitmap = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, row_bytes, 32 ) ns_image.addRepresentation_(ns_bitmap) ns_bitmap_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(ns_bitmap) ns_graphics_context = FlippedNSGraphicsContext.alloc().initWithBase_(ns_bitmap_context) ns_tr = NSAffineTransform.transform() ns_tr.translateXBy_yBy_(0.0, height) ns_tr.scaleXBy_yBy_(1.0, -1.0) # Using __class__ to get +saveGraphicsState instead of -saveGraphicsState NSGraphicsContext.__class__.saveGraphicsState() try: NSGraphicsContext.setCurrentContext_(ns_graphics_context) ns_tr.concat() finally: NSGraphicsContext.__class__.restoreGraphicsState() self._init_with_ns_image(ns_image, flipped=True) # False) self._ns_bitmap_image_rep = ns_bitmap self._ns_graphics_context = ns_graphics_context
def drawFriends(self, layer): try: friends = self.currentWindow.glyphList.get() except: friends = None c = 0 if friends: for friend in friends: if friend.get("Visibility", 0): g = friend["layer"] if g.completeBezierPath is not None: bP = g.completeBezierPath.copy() t = NSAffineTransform.transform() if self.alignment == 1: translateX = layer.width / 2.0 - g.width / 2.0 + friend[ "Position"] elif self.alignment == 2: translateX = layer.width - g.width + friend[ "Position"] else: translateX = int(friend["Position"]) t.translateXBy_yBy_(translateX, 0.0) tM = t.transformStruct() bP.applyTransform_(tM) NSColor.colorWithDeviceRed_green_blue_alpha_( 1.0, 0.73, c, 0.35).set() bP.fill() c = (c + 0.27) % 1.0
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 MenuImageRepresentationFactory(glyph): font = glyph.font cellHeight = 60.0 cellWidth = 60.0 imageSize = (cellWidth, cellHeight) availableHeight = cellHeight * .6 yBuffer = int((cellHeight - availableHeight) / 2) upm = font.info.unitsPerEm descender = font.info.descender scale = availableHeight / upm glyphWidth = glyph.width * scale centerOffset = (cellWidth - glyphWidth) * 0.5 path = glyph.getRepresentation("defconAppKit.NSBezierPath") image = NSImage.alloc().initWithSize_(imageSize) image.lockFocus() bounds = ((0, 0), imageSize) MenuImageBackgroundColor.set() NSRectFillUsingOperation(bounds, NSCompositeSourceOver) transform = NSAffineTransform.transform() transform.translateXBy_yBy_(centerOffset, yBuffer) transform.scaleXBy_yBy_(scale, scale) transform.translateXBy_yBy_(0, abs(descender)) transform.concat() MenuImageGlyphColor.set() path.fill() image.unlockFocus() return image
def __init__(self, width, height): GPixmap.__init__(self) #ns_size = NSSize(width, height) #ns_image = NSImage.alloc().initWithSize_(ns_size) ns_image = NSImage.alloc().init() ns_image.setCacheMode_(NSImageCacheNever) row_bytes = 4 * width ns_bitmap = NSBitmapImageRep.alloc().\ initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, row_bytes, 32) ns_image.addRepresentation_(ns_bitmap) ns_bitmap_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(ns_bitmap) ns_graphics_context = FlippedNSGraphicsContext.alloc().initWithBase_(ns_bitmap_context) ns_tr = NSAffineTransform.transform() ns_tr.translateXBy_yBy_(0.0, height) ns_tr.scaleXBy_yBy_(1.0, -1.0) # Using __class__ to get +saveGraphicsState instead of -saveGraphicsState NSGraphicsContext.__class__.saveGraphicsState() try: NSGraphicsContext.setCurrentContext_(ns_graphics_context) ns_tr.concat() finally: NSGraphicsContext.__class__.restoreGraphicsState() self._init_with_ns_image(ns_image, flipped = True) #False) self._ns_bitmap_image_rep = ns_bitmap self._ns_graphics_context = ns_graphics_context
def getAffineTransform(angle, centerX, centerY): u"""Rotates at angle around point by shifting object to origin first, then putting it back after.""" at = NSAffineTransform.transform() at.translateXBy_yBy_(centerX, centerY) at.rotateByDegrees_(angle) at.translateXBy_yBy_(-centerX, -centerY) return at
def getAffineTransform(angle, point): u"""Rotates at angle around point.""" x = point[0] y = point[1] at = NSAffineTransform.transform() at.translateXBy_yBy_(x, y) at.rotateByDegrees_(angle) at.translateXBy_yBy_(-x, -y) return at
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 drawGlyphImage(glyph, scale, rect, backgroundColor=None): if glyph.image.fileName is None: return context = NSGraphicsContext.currentContext() context.saveGraphicsState() aT = NSAffineTransform.transform() aT.setTransformStruct_(glyph.image.transformation) aT.concat() image = glyph.image.getRepresentation("defconAppKit.NSImage") image.drawAtPoint_fromRect_operation_fraction_( (0, 0), ((0, 0), image.size()), NSCompositeSourceOver, 1.0) context.restoreGraphicsState()
def drawGlyphImage(glyph, scale, rect, backgroundColor=None): if glyph.image.fileName is None: return context = NSGraphicsContext.currentContext() context.saveGraphicsState() aT = NSAffineTransform.transform() aT.setTransformStruct_(glyph.image.transformation) aT.concat() image = glyph.image.getRepresentation("defconAppKit.NSImage") image.drawAtPoint_fromRect_operation_fraction_( (0, 0), ((0, 0), image.size()), NSCompositeSourceOver, 1.0 ) context.restoreGraphicsState()
def slantLayers(layers, angle): Font.disableUpdateInterface() xHeight = layers[0].associatedFontMaster().xHeight transform = NSAffineTransform.new() slant = math.tan(skewAngle * math.pi / 180.0) transform.shearXBy_atCenter_(slant, -xHeight / 2.0) for layer in selectedLayers: for path in layer.paths: for node in path.nodes: node.position = transform.transformPoint_(node.position) for anchor in layer.anchors: anchor.position = transform.transformPoint_(anchor.position) Font.enableUpdateInterface()
def drawCoords(coords, centerX, centerY, rotate=45): path = BezierPath() at = NSAffineTransform.transform() at.translateXBy_yBy_(centerX, centerY) at.rotateByDegrees_(rotate) at.translateXBy_yBy_(-centerX, -centerY) p0 = coords[0] path.moveTo((p0[0], p0[1])) for coord in coords[1:]: path.lineTo((coord[0], coord[1])) nsPath = path.getNSBezierPath() nsPath = at.transformBezierPath_(nsPath) path.setNSBezierPath(nsPath) drawPath(path)
def pathCountInKernPair( firstGlyphName, secondGlyphName, thisFont, thisFontMasterID, minDistance ): #ligatureName = "%s_%s" % ( nameUntilFirstPeriod(firstGlyphName), nameUntilFirstPeriod(secondGlyphName) ) #newGlyph = thisFont.newGlyphWithName_changeName_( "_deleteMe", False ) ligatureLayer = thisFont.glyphs[secondGlyphName].layers[thisFontMasterID].copyDecomposedLayer() addedLayer = thisFont.glyphs[firstGlyphName].layers[thisFontMasterID].copyDecomposedLayer() # position of right component: kerning = effectiveKerning( firstGlyphName, secondGlyphName, thisFont, thisFontMasterID ) rightShift = NSAffineTransform.transform() rightShift.translateXBy_yBy_( addedLayer.width + kerning - minDistance, 0.0 ) ligatureLayer.transform_checkForSelection_( rightShift, False ) for addedPath in addedLayer.paths: ligatureLayer.addPath_( addedPath.copy() ) return pathCountOnLayer( ligatureLayer )
def _drawArrow(self, position, kind, size, vector=(-1, 1), level="e"): if vector is None: vector = (-1, 1) angle = atan2(vector[0], -vector[1]) size *= 2 x, y = position head_ratio = 0.7 w = size * 0.5 tail_width = 0.3 chin = 0.5 * (w - w * tail_width) # part under the head if level == "e": arrow_color = error_color else: arrow_color = warning_color NSColor.colorWithCalibratedRed_green_blue_alpha_(*arrow_color).set() t = NSAffineTransform.transform() t.translateXBy_yBy_(x, y) t.rotateByRadians_(angle) myPath = NSBezierPath.alloc().init() myPath.moveToPoint_((0, 0)) myPath.relativeLineToPoint_((-size * head_ratio, w * 0.5)) myPath.relativeLineToPoint_((0, -chin)) myPath.relativeLineToPoint_((-size * (1 - head_ratio), 0)) myPath.relativeLineToPoint_((0, -w * tail_width)) myPath.relativeLineToPoint_((size * (1 - head_ratio), 0)) myPath.relativeLineToPoint_((0, -chin)) myPath.closePath() myPath.transformUsingAffineTransform_(t) myPath.fill() percent = 1 if not self.show_labels: percent = ( -distance_between_points(self.mouse_position, position) / size * 2 + 2) if self.show_labels or percent > 0.2: self._drawTextLabel( transform=t, text=kind, size=size, vector=vector, percent=percent, )
def _drawUnspecified(self, position, kind, size, vector=(-1, 1), level="e"): if vector is None: vector = (-1, 1) angle = atan2(vector[1], vector[0]) circle_size = size * 1.3 x, y = position if level == "e": arrow_color = error_color else: arrow_color = warning_color NSColor.colorWithCalibratedRed_green_blue_alpha_(*arrow_color).set() t = NSAffineTransform.transform() t.translateXBy_yBy_(x, y) t.rotateByRadians_(angle) myPath = NSBezierPath.alloc().init() myPath.setLineWidth_(0) myPath.appendBezierPathWithOvalInRect_( NSMakeRect( x - 0.5 * circle_size, y - 0.5 * circle_size, circle_size, circle_size, )) myPath.stroke() percent = (-distance_between_points(self.mouse_position, position) / size * 2 + 2) if self.show_labels or percent > 0.2: self._drawTextLabel( transform=t, text=kind, size=size, vector=vector, percent=percent, )
def TransformImagesMain(self, sender): try: Font = Glyphs.font selectedLayers = Font.selectedLayers if sender == self.w.backButton: factor = -1.0 elif sender == self.w.runButton: factor = 1.0 for thisLayer in selectedLayers: thisImage = thisLayer.backgroundImage if thisImage: moveXpreScaled, moveYpreScaled, scaleXfix, scaleYfix = self.w.move_X.get( ), self.w.move_Y.get(), self.w.scale_X.get( ), self.w.scale_Y.get() if moveXpreScaled == "": moveXpreScaled = 0 if moveYpreScaled == "": moveYpreScaled = 0 if scaleXfix == "": scaleXfix = 0 if scaleYfix == "": scaleYfix = 0 moveX, moveY = float(moveXpreScaled) * factor, float( moveYpreScaled) * factor scaleX, scaleY = getScale(scaleXfix, factor), getScale( scaleYfix, factor) ScaleAndMoveTransform = NSAffineTransform.transform() ScaleAndMoveTransform.setTransformStruct_( thisImage.transformStruct()) ScaleAndMoveTransform.scaleXBy_yBy_(scaleX, scaleY) ScaleAndMoveTransform.translateXBy_yBy_(moveX, moveY) thisImage.setTransformStruct_( ScaleAndMoveTransform.transformStruct()) if not self.SavePreferences(self): print("Note: could not write preferences.") # self.w.close() except Exception as e: raise e
def _drawArrow(self, position, kind, size, vector=(-1, 1)): if vector is None: vector = (-1, 1) angle = atan2(vector[0], -vector[1]) size *= 2 x, y = position head_ratio = 0.7 w = size * 0.5 tail_width = 0.3 chin = 0.5 * (w - w * tail_width) # part under the head NSColor.colorWithCalibratedRed_green_blue_alpha_(0.9, 0.1, 0.0, 0.85).set() t = NSAffineTransform.transform() t.translateXBy_yBy_(x, y) t.rotateByRadians_(angle) myPath = NSBezierPath.alloc().init() myPath.moveToPoint_((0, 0)) myPath.relativeLineToPoint_((-size * head_ratio, w * 0.5)) myPath.relativeLineToPoint_((0, -chin)) myPath.relativeLineToPoint_((-size * (1 - head_ratio), 0)) myPath.relativeLineToPoint_((0, -w * tail_width)) myPath.relativeLineToPoint_((size * (1 - head_ratio), 0)) myPath.relativeLineToPoint_((0, -chin)) myPath.closePath() myPath.transformUsingAffineTransform_(t) myPath.fill() if self.show_labels or distance_between_points(self.mouse_position, position) < size: self._drawTextLabel( transform=t, text=kind, size=size, vector=vector, )
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 height *= scale x, y = pt f = 1 if flipped: f = -1 if xAlign == "center": x -= width / 2 elif xAlign == "right": x -= width if yAlign == "center": y -= height / 2 * f elif yAlign == "top": y -= height * f pt = (x, y) context = NSGraphicsContext.currentContext() context.saveGraphicsState() transform = NSAffineTransform.transform() transform.translateXBy_yBy_(pt[0], pt[1]) if flipped: s = -scale else: s = scale transform.scaleXBy_yBy_(scale, s) transform.concat() text.drawAtPoint_((0, 0)) context.restoreGraphicsState()
def _drawUnspecified(self, position, kind, size, vector = (-1, 1)): if vector is None: vector = (-1, 1) angle = atan2(vector[1], vector[0]) circle_size = size * 1.3 x, y = position NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.9, 0.1, 0.0, 0.85 ).set() t = NSAffineTransform.transform() t.translateXBy_yBy_(x, y) t.rotateByRadians_(angle) myPath = NSBezierPath.alloc().init() myPath.setLineWidth_( 0 ) myPath.appendBezierPathWithOvalInRect_( NSMakeRect( x - 0.5 * circle_size, y - 0.5 * circle_size, circle_size, circle_size ) ) myPath.stroke() if self.show_labels or distance_between_points(self.mouse_position, position) < size: self._drawTextLabel( transform = t, text = kind, size = size, angle = angle, )
def as_matrix(self, normalize=False, binarize=False): """Renders the glyph as a matrix. By default, the matrix values are integer pixel greyscale values in the range 0 to 255, but they can be normalized or turned into binary values with the appropriate keyword arguments. The matrix is returned as a `GlyphRendering` object which can be further manipulated.""" box_height = int(self.font.full_height_px) box_width = int(self.ink_width) b = NSBitmapImageRep.alloc( ).initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_( None, box_width, box_height, 8, 1, False, False, NSCalibratedWhiteColorSpace, 0, 0) ctx = NSGraphicsContext.graphicsContextWithBitmapImageRep_(b) assert (ctx) NSGraphicsContext.setCurrentContext_(ctx) NSColor.whiteColor().setFill() p2 = NSBezierPath.bezierPath() p2.appendBezierPath_(self.layer.completeBezierPath) t = NSAffineTransform.transform() t.translateXBy_yBy_(-self.lsb, -self.font.descender * self.font.scale_factor) t.scaleBy_(self.font.scale_factor) p2.transformUsingAffineTransform_(t) p2.fill() png = b.representationUsingType_properties_(NSPNGFileType, None) png.writeToFile_atomically_("/tmp/foo.png", False) Z = np.array(b.bitmapData()) box_width_up = Z.shape[0] / box_height Z = Z.reshape((box_height, box_width_up))[0:box_height, 0:box_width] if normalize or binarize: Z = Z / 255.0 if binarize: Z = Z.astype(int) return GlyphRendering.init_from_numpy(self, Z)
def _drawArrow(self, position, kind, size, vector = (-1, 1)): if vector is None: vector = (-1, 1) angle = atan2(vector[0], -vector[1]) size *= 2 x, y = position head_ratio = 0.7 w = size * 0.5 tail_width = 0.3 chin = 0.5 * (w - w * tail_width) # part under the head NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.9, 0.1, 0.0, 0.85 ).set() t = NSAffineTransform.transform() t.translateXBy_yBy_(x, y) t.rotateByRadians_(angle) myPath = NSBezierPath.alloc().init() myPath.moveToPoint_( (0, 0) ) myPath.relativeLineToPoint_( (-size * head_ratio, w * 0.5) ) myPath.relativeLineToPoint_( (0, -chin) ) myPath.relativeLineToPoint_( (-size * (1 - head_ratio), 0) ) myPath.relativeLineToPoint_( (0, -w * tail_width) ) myPath.relativeLineToPoint_( (size * (1 - head_ratio), 0) ) myPath.relativeLineToPoint_( (0, -chin) ) myPath.closePath() myPath.transformUsingAffineTransform_(t) myPath.fill() if self.show_labels or distance_between_points(self.mouse_position, position) < size: self._drawTextLabel( transform = t, text = kind, size = size, vector = vector, )
def vector_rotateByDegrees_(vec, deg): matrix = NSAffineTransform.transform() matrix.rotateByDegrees_(deg) return matrix.transformPoint_(vec)
def vector_setMagnitude_(vec, mag): matrix = NSAffineTransform.transform() matrix.scaleBy_(1.0 / vectorMagnitude_(vec)) # make unit length matrix.scaleBy_(mag) return matrix.transformPoint_(vec)
def translate(self, dx, dy): matrix = NSAffineTransform.transform() matrix.translateXBy_yBy_(dx, dy) self._ns_path.transformUsingAffineTransform_(matrix) self.transformstack[-1].append(["translate", dx, dy])
def drawRectRightToLeft_(self, rect): self._alternateRects = {} # draw the background bounds = self.bounds() self._backgroundColor.set() NSRectFill(bounds) # create some reusable values scale = self._scale descender = self._descender upm = self._upm scrollWidth = bounds.size[0] # offset for the buffer ctx = NSGraphicsContext.currentContext() ctx.saveGraphicsState() aT = NSAffineTransform.transform() aT.translateXBy_yBy_(scrollWidth - self._bufferLeft, self._bufferTop) aT.concat() # offset for the descender aT = NSAffineTransform.transform() aT.scaleBy_(scale) aT.translateXBy_yBy_(0, descender) aT.concat() # flip flipTransform = NSAffineTransform.transform() flipTransform.translateXBy_yBy_(0, upm) flipTransform.scaleXBy_yBy_(1.0, -1.0) flipTransform.concat() # set the glyph color self._glyphColor.set() # draw the records left = scrollWidth - self._bufferLeft bottom = self._bufferTop height = upm * scale previousXA = 0 for recordIndex, glyphRecord in enumerate(reversed( self._glyphRecords)): glyph = glyphRecord.glyph w = glyphRecord.advanceWidth h = glyphRecord.advanceHeight xP = glyphRecord.xPlacement yP = glyphRecord.yPlacement xA = glyphRecord.xAdvance yA = glyphRecord.yAdvance # handle offsets from the record bottom += yP * scale glyphHeight = height + ((h + yA) * scale) glyphLeft = left + ((-w + xP - xA) * scale) glyphWidth = (-w - xA) * scale # store the glyph rect for the alternate menu rect = ((glyphLeft, bottom), (glyphWidth, glyphHeight)) self._alternateRects[rect] = recordIndex self._currentZeroZeroPoint = NSPoint( glyphLeft, bottom + height + (descender * scale)) # handle the placement aT = NSAffineTransform.transform() if xP: xP += previousXA aT.translateXBy_yBy_(-w - xA + xP, yP) aT.concat() # draw the glyph rect = ((-w + xA - xP, descender - yP), (w, upm)) self.drawGlyph(glyph, rect, alternate=bool(glyphRecord.alternates)) # shift for the next glyph aT = NSAffineTransform.transform() aT.translateXBy_yBy_(-xP, h + yA - yP) aT.concat() left += (-w - xP - xA) * scale previousXA = xA ctx.restoreGraphicsState()
def move(self): dx,dy = self.vector matrix = NSAffineTransform.transform() matrix.translateXBy_yBy_(dx,dy) self.position = matrix.transformPoint_(self.position) self.transformUsingAffineTransform_(matrix)
def scale(self, sx, sy): matrix = NSAffineTransform.transform() matrix.scaleXBy_yBy_(sx, sy) self._ns_path.transformUsingAffineTransform_(matrix) self.transformstack[-1].append(["scale", sx, sy])
def drawRect_(self, rect): needCalc = False if self.superview( ) and self._fitToFrame != self.superview().visibleRect().size: needCalc = True if self.inLiveResize(): needCalc = True if needCalc: self.recalculateFrame() self.drawBackground() if self._glyph is None: return # apply the overall scale transform = NSAffineTransform.transform() transform.scaleBy_(self._scale) transform.concat() # move into position visibleWidth = self.bounds().size[0] width = self._glyph.width * self._scale diff = visibleWidth - width xOffset = round((diff / 2) * self._inverseScale) yOffset = self._verticalCenterYBuffer * self._inverseScale yOffset -= self._descender # @@@ yOffset -= 270 xOffset += 130 transform = NSAffineTransform.transform() transform.translateXBy_yBy_(xOffset, yOffset) transform.concat() # store the current drawing rect w, h = self.bounds().size w *= self._inverseScale h *= self._inverseScale justInCaseBuffer = 1 * self._inverseScale xOffset += justInCaseBuffer yOffset += justInCaseBuffer w += justInCaseBuffer * 2 h += justInCaseBuffer * 2 self._drawingRect = ((-xOffset, -yOffset), (w, h)) # gather the layers layerSet = self._glyph.layerSet if layerSet is None: layers = [(self._glyph, None)] else: glyphName = self._glyph.name layers = [] for layerName in reversed(layerSet.layerOrder): layer = layerSet[layerName] if glyphName not in layer: continue glyph = layer[glyphName] if glyph == self._glyph: layerName = None layers.append((glyph, layerName)) for glyph, layerName in layers: # draw the image if self.getDrawingAttribute_layerName_("showGlyphImage", layerName): self.drawImage(glyph, layerName) # draw the blues if layerName is None and self.getDrawingAttribute_layerName_( "showFontPostscriptBlues", None): self.drawBlues(glyph, layerName) if layerName is None and self.getDrawingAttribute_layerName_( "showFontPostscriptFamilyBlues", None): self.drawFamilyBlues(glyph, layerName) # draw the margins if self.getDrawingAttribute_layerName_("showGlyphMargins", layerName): self.drawMargins(glyph, layerName) # draw the vertical metrics if layerName is None and self.getDrawingAttribute_layerName_( "showFontVerticalMetrics", None): self.drawVerticalMetrics(glyph, layerName) # draw the glyph if self.getDrawingAttribute_layerName_( "showGlyphFill", layerName) or self.getDrawingAttribute_layerName_( "showGlyphStroke", layerName): self.drawFillAndStroke(glyph, layerName) if self.getDrawingAttribute_layerName_( "showGlyphOnCurvePoints", layerName) or self.getDrawingAttribute_layerName_( "showGlyphOffCurvePoints", layerName): self.drawPoints(glyph, layerName) if self.getDrawingAttribute_layerName_("showGlyphAnchors", layerName): self.drawAnchors(glyph, layerName)
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 scale(self, sx, sy): matrix = NSAffineTransform.transform() matrix.scaleXBy_yBy_(sx, sy) self._ns_path.transformUsingAffineTransform_(matrix) self.transformstack[-1].append(["scale",sx,sy])
def translate(self, dx, dy): matrix = NSAffineTransform.transform() matrix.translateXBy_yBy_(dx, dy) self._ns_path.transformUsingAffineTransform_(matrix) self.transformstack[-1].append(["translate",dx,dy])
def drawRect_(self, rect): ## needs to be `drawRect_` -- nothing else bounds = self.bounds() # thisUPM = self._layer.parent.parent.upm scaleFactor = self._scaleFactor thisUPM = self._upm * scaleFactor rectX, rectY, rectWidth, rectHeight = 0, 0, thisUPM, thisUPM self.rect = rect # self._layer.drawInFrame_(bounds) # used in Georgs GlyphView try: layerWidth = self._layer.width * scaleFactor descender = self._layer.glyphMetrics()[3] * scaleFactor ## this order is important! Wont work the other way around try: # pre Glyphs 2.3 bezierPathOnly = self._layer.copy().bezierPath() # Path Only bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath() # Path & Components except: # Glyphs 2.3 bezierPathOnly = self._layer.copy().bezierPath # Path Only bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath # Path & Components scale = NSAffineTransform.transform() scale.translateXBy_yBy_( rectWidth/2 - (layerWidth / 2.0) + self._margin/2, -descender + self._margin/2 ) scale.scaleBy_( scaleFactor ) if bezierPathWithComponents: bezierPathWithComponents.transformUsingAffineTransform_( scale ) if bezierPathOnly: bezierPathOnly.transformUsingAffineTransform_( scale ) ## DRAW COMPONENTS IN GRAY NSColor.darkGrayColor().set() # lightGrayColor bezierPathWithComponents.fill() ## CHANGE COLOR FOR NON-EXPORTED GLYPHS thisGlyph = self._layer.parent if thisGlyph.export: NSColor.blackColor().set() ## DRAW ONLY PATH IN BLACK if bezierPathOnly: bezierPathOnly.fill() else: NSColor.orangeColor().set() bezierPathWithComponents.fill() # print self.bounds() ## AUTO-WIDTH LABEL if self._layer.hasAlignedWidth(): paragraphStyle = NSMutableParagraphStyle.alloc().init() paragraphStyle.setAlignment_(2) ## 0=L, 1=R, 2=C, 3=justified attributes = {} attributes[NSFontAttributeName] = NSFont.systemFontOfSize_(10) attributes[NSForegroundColorAttributeName] = NSColor.lightGrayColor() attributes[NSParagraphStyleAttributeName] = paragraphStyle String = NSAttributedString.alloc().initWithString_attributes_("Auto-Width", attributes) # String.drawAtPoint_((rectWidth, 0)) NSColor.redColor().set() # NSRectFill(((0, 0), (self.rect.size.width, 15))) String.drawInRect_(((0, 0), (self.rect.size.width, 15))) except: # pass print traceback.format_exc()
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 _drawArrow(position, kind, size, vector=(-1, 1), label_size=1): angle = atan2(vector[0], -vector[1]) print vector, "%0.2f°" % degrees(angle) x, y = position head_ratio = 0.7 w = size * 0.5 tail_width = 0.3 chin = 0.5 * (w - w * tail_width) # part under the head NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.9, 0.1, 0.0, 0.85 ).set() t = NSAffineTransform.transform() t.translateXBy_yBy_(x, y) t.rotateByRadians_(angle) myPath = NSBezierPath.alloc().init() myPath.moveToPoint_( (0, 0) ) myPath.relativeLineToPoint_( (-size * head_ratio, w * 0.5) ) myPath.relativeLineToPoint_( (0, -chin) ) myPath.relativeLineToPoint_( (-size * (1 - head_ratio), 0) ) myPath.relativeLineToPoint_( (0, -w * tail_width) ) myPath.relativeLineToPoint_( (size * (1 - head_ratio), 0) ) myPath.relativeLineToPoint_( (0, -chin) ) myPath.closePath() myPath.transformUsingAffineTransform_(t) myPath.fill() drawPath(myPath) myString = NSString.string().stringByAppendingString_(kind) attrs = { NSFontAttributeName: NSFont.systemFontOfSize_(label_size), NSForegroundColorAttributeName: NSColor.colorWithCalibratedRed_green_blue_alpha_( 0.4, 0.4, 0.6, 0.7 ), } bbox = myString.sizeWithAttributes_(attrs) #print bbox p = NSPoint() bw = bbox.width bh = bbox.height #print " ", cos(angle) if -0.5 * pi < angle <= 0.5 * pi: p.x, p.y = ( - size - 20 - bh/2 * sin(angle) - bw/2 * cos(angle), # + bw/2.0 * cos(angle - pi) 0 ) else: p.x, p.y = ( - size - 20 + bh/2 * sin(angle) + bw/2 * cos(angle), # + bw/2.0 * cos(angle - pi) 0, ) p = t.transformPoint_(p) #print p #fontSize(label_size) #text(kind, (p.x - bbox.width/2, p.y - bbox.height/2)) fill(None) rect(p.x - bbox.width/2, p.y - bbox.height/2, bbox.width, bbox.height) fill(1, 0, 0) #oval(p.x -bh/2.0 , p.y -bh/2.0, bh, bh) #myString.drawAtPoint_withAttributes_(p, attrs) rr = NSRect(origin=(p.x -bh/2.0, p.y -bw/2.0), size=(bw, bh)) #print rr myString.drawInRect_withAttributes_(rr, attrs) myString.drawAtPoint_withAttributes_(p, attrs)
def addCountBadgeToIcon(count, iconImage=None): if iconImage is None: iconImage = NSImage.alloc().initWithSize_((40, 40)) iconImage.lockFocus() NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 1, .5).set() path = NSBezierPath.bezierPath() path.appendBezierPathWithOvalInRect_(((0, 0), iconImage.size())) path.fill() iconImage.unlockFocus() # badge text textShadow = NSShadow.alloc().init() textShadow.setShadowOffset_((2, -2)) textShadow.setShadowColor_( NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 0, 1.0)) textShadow.setShadowBlurRadius_(2.0) paragraph = NSMutableParagraphStyle.alloc().init() paragraph.setAlignment_(NSCenterTextAlignment) paragraph.setLineBreakMode_(NSLineBreakByCharWrapping) attributes = { NSFontAttributeName: NSFont.boldSystemFontOfSize_(12.0), NSForegroundColorAttributeName: NSColor.whiteColor(), NSParagraphStyleAttributeName: paragraph, NSShadowAttributeName: textShadow } text = NSAttributedString.alloc().initWithString_attributes_( str(count), attributes) rectWidth, rectHeight = NSString.stringWithString_( str(count)).sizeWithAttributes_(attributes) rectWidth = int(round(rectWidth + 8)) rectHeight = int(round(rectHeight + 4)) rectLeft = 0 rectBottom = 0 # badge shadow badgeShadow = NSShadow.alloc().init() badgeShadow.setShadowOffset_((0, -2)) badgeShadow.setShadowColor_(NSColor.blackColor()) badgeShadow.setShadowBlurRadius_(4.0) # badge path badgePath = roundedRectBezierPath( ((rectLeft, rectBottom), (rectWidth, rectHeight)), 3) # badge image badgeWidth = rectWidth + 3 badgeHeight = rectHeight + 3 badgeImage = NSImage.alloc().initWithSize_((badgeWidth, badgeHeight)) badgeImage.lockFocus() transform = NSAffineTransform.transform() transform.translateXBy_yBy_(1.5, 1.5) transform.concat() NSColor.colorWithCalibratedRed_green_blue_alpha_(.2, .2, .25, 1.0).set() badgePath.fill() NSColor.colorWithCalibratedRed_green_blue_alpha_(.8, .8, .9, 1.0).set() badgePath.setLineWidth_(1.0) badgePath.stroke() text.drawInRect_(((0, -1), (rectWidth, rectHeight))) badgeImage.unlockFocus() # make the composite image imageWidth, imageHeight = iconImage.size() imageWidth += (badgeWidth - 15) imageHeight += 10 badgeLeft = imageWidth - badgeWidth - 3 badgeBottom = 3 image = NSImage.alloc().initWithSize_((imageWidth, imageHeight)) image.lockFocus() context = NSGraphicsContext.currentContext() # icon iconImage.drawAtPoint_fromRect_operation_fraction_( (0, 10), ((0, 0), iconImage.size()), NSCompositeSourceOver, 1.0) # badge context.saveGraphicsState() badgeShadow.set() badgeImage.drawAtPoint_fromRect_operation_fraction_( (badgeLeft, badgeBottom), ((0, 0), badgeImage.size()), NSCompositeSourceOver, 1.0) context.restoreGraphicsState() # done image.unlockFocus() return image
def drawRectRightToLeft_(self, rect): self._alternateRects = {} # draw the background bounds = self.bounds() self._backgroundColor.set() NSRectFill(bounds) # create some reusable values scale = self._scale descender = self._descender upm = self._upm scrollWidth = bounds.size[0] # offset for the buffer ctx = NSGraphicsContext.currentContext() ctx.saveGraphicsState() aT = NSAffineTransform.transform() aT.translateXBy_yBy_(scrollWidth - self._bufferLeft, self._bufferTop) aT.concat() # offset for the descender aT = NSAffineTransform.transform() aT.scaleBy_(scale) aT.translateXBy_yBy_(0, descender) aT.concat() # flip flipTransform = NSAffineTransform.transform() flipTransform.translateXBy_yBy_(0, upm) flipTransform.scaleXBy_yBy_(1.0, -1.0) flipTransform.concat() # set the glyph color self._glyphColor.set() # draw the records left = scrollWidth - self._bufferLeft bottom = self._bufferTop height = upm * scale previousXA = 0 for recordIndex, glyphRecord in enumerate(reversed(self._glyphRecords)): glyph = glyphRecord.glyph w = glyphRecord.advanceWidth h = glyphRecord.advanceHeight xP = glyphRecord.xPlacement yP = glyphRecord.yPlacement xA = glyphRecord.xAdvance yA = glyphRecord.yAdvance # handle offsets from the record bottom += yP * scale glyphHeight = height + ((h + yA) * scale) glyphLeft = left + ((-w + xP - xA) * scale) glyphWidth = (-w - xA) * scale # store the glyph rect for the alternate menu rect = ((glyphLeft, bottom), (glyphWidth, glyphHeight)) self._alternateRects[rect] = recordIndex self._currentZeroZeroPoint = NSPoint(glyphLeft, bottom + height + (descender * scale)) # handle the placement aT = NSAffineTransform.transform() if xP: xP += previousXA aT.translateXBy_yBy_(-w - xA + xP, yP) aT.concat() # draw the glyph rect = ((-w + xA - xP, descender - yP), (w, upm)) self.drawGlyph(glyph, rect, alternate=bool(glyphRecord.alternates)) # shift for the next glyph aT = NSAffineTransform.transform() aT.translateXBy_yBy_(-xP, h + yA - yP) aT.concat() left += (-w - xP - xA) * scale previousXA = xA ctx.restoreGraphicsState()
def rotate(self, rotation): matrix = NSAffineTransform.transform() matrix.rotateByDegrees_(rotation) self._ns_path.transformUsingAffineTransform_(matrix) self.transformstack[-1].append(["rotate",rotation])
def drawRect_(self, rect): self.wrapper._backColour.set() NSBezierPath.fillRect_(rect) sizes = [ 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 24, 28, 32, 36, 48, 60, 72, 90, 120 ] lineSpace = 8 tab = 30 w = NSWidth(self.frame()) h = NSHeight(self.frame()) glyphNames = self.wrapper._glyphsList insIndex = self.wrapper._instanceIndex if insIndex == 0: font = Glyphs.font m = font.selectedFontMaster else: instance = Glyphs.font.instances[insIndex - 1] font = self.wrapper.instances.get(instance.name) if font is None: font = instance.interpolatedFont self.wrapper.instances[instance.name] = font m = font.masters[0] fullPath = NSBezierPath.alloc().init() advance = 0 self.wrapper._foreColour.set() try: for i, glyphName in enumerate(glyphNames): glyph = self.glyphForName(glyphName, font) if glyph: layer = glyph.layers[m.id] layerPath = layer.completeBezierPath kernValue = 0 # kerning check if i + 1 < len(glyphNames): nextGlyphName = glyphNames[i + 1] nextGlyph = self.glyphForName(nextGlyphName, font) if nextGlyph: nextLayer = nextGlyph.layers[m.id] if nextLayer: kernValue = getKernValue(layer, nextLayer) if kernValue > 10000: kernValue = 0 transform = NSAffineTransform.transform() transform.translateXBy_yBy_(advance, 0) layerPath.transformUsingAffineTransform_(transform) advance += layer.width + kernValue fullPath.appendBezierPath_(layerPath) except: print(traceback.format_exc()) if fullPath is None: return try: sSum = 0 upm = float(font.upm) for i, s in enumerate(sizes): sSum += s + s / 4 transform = NSAffineTransform.transform() transform.scaleBy_(s / upm) transform.translateXBy_yBy_(tab * upm / s, (h - s - sSum) * upm / s) self.drawText(str(s), self.wrapper._foreColour, 10, h - s - sSum - 2) fullPath.transformUsingAffineTransform_(transform) fullPath.fill() transform.invert() fullPath.transformUsingAffineTransform_(transform) except StandardError: print(traceback.format_exc())
def drawRect_(self, rect): ## must be `drawRect_` - nothing else bounds = self.bounds() scaleFactor = self._scaleFactor thisUPM = self._upm * scaleFactor # = self._layer.parent.parent.upm rectX, rectY, rectWidth, rectHeight = 0, 0, thisUPM, thisUPM self.rect = rect # self._layer.drawInFrame_(bounds) # used in Georgs GlyphView try: thisGlyph = self._layer.parent layerWidth = self._layer.width * scaleFactor descender = self._layer.glyphMetrics()[3] * scaleFactor # ## This order is important! Wont work the other way around. # try: # pre Glyphs 2.3 # bezierPathOnly = self._layer.copy().bezierPath() # Path Only # bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath() # Path & Components # except: # Glyphs 2.3 # bezierPathOnly = self._layer.copy().bezierPath # Path Only # bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath # Path & Components ## This order is important! Wont work the other way around. try: # Glyphs 2.3 bezierPathOnly = self._layer.copy().bezierPath # Path Only bezierPathWithComponents = self._layer.copyDecomposedLayer().bezierPath # Path & Components except: # Glyphs 2.4 bezierPathOnly = self._layer.copy().bezierPath # Path Only bezierPathWithComponents = self._layer.completeBezierPath # Path & Components # Set the scale #-------------- scale = NSAffineTransform.transform() scale.translateXBy_yBy_( rectWidth/2 - (layerWidth / 2.0) + self._margin/2, -descender + self._margin/2 ) scale.scaleBy_( scaleFactor ) if bezierPathWithComponents: bezierPathWithComponents.transformUsingAffineTransform_( scale ) if bezierPathOnly: bezierPathOnly.transformUsingAffineTransform_( scale ) # Draw components in gray #------------------------ NSColor.darkGrayColor().set() # lightGrayColor bezierPathWithComponents.fill() # Draw only path in black #------------------------ if thisGlyph.export: NSColor.blackColor().set() if bezierPathOnly: bezierPathOnly.fill() # Draw non-exported glyphs in orange #----------------------------------- else: NSColor.orangeColor().set() bezierPathWithComponents.fill() # AUTO-WIDTH LABEL #----------------- if self._layer.hasAlignedWidth(): paragraphStyle = NSMutableParagraphStyle.alloc().init() paragraphStyle.setAlignment_(2) ## 0=L, 1=R, 2=C, 3=justified attributes = {} attributes[NSFontAttributeName] = NSFont.systemFontOfSize_(10) attributes[NSForegroundColorAttributeName] = NSColor.lightGrayColor() attributes[NSParagraphStyleAttributeName] = paragraphStyle String = NSAttributedString.alloc().initWithString_attributes_("Auto-Width", attributes) # String.drawAtPoint_((rectWidth, 0)) NSColor.redColor().set() # NSRectFill(((0, 0), (self.rect.size.width, 15))) String.drawInRect_(((0, 0), (self.rect.size.width, 15))) except: pass # print traceback.format_exc()
def drawRect_(self, rect): needCalc = False if self.superview() and self._fitToFrame != self.superview().visibleRect().size: needCalc = True if self.inLiveResize(): needCalc = True if needCalc: self.recalculateFrame() self.drawBackground() if self._glyph is None: return # apply the overall scale transform = NSAffineTransform.transform() transform.scaleBy_(self._scale) transform.concat() # move into position visibleWidth = self.bounds().size[0] width = self._glyph.width * self._scale diff = visibleWidth - width xOffset = round((diff / 2) * self._inverseScale) yOffset = self._verticalCenterYBuffer * self._inverseScale yOffset -= self._descender transform = NSAffineTransform.transform() transform.translateXBy_yBy_(xOffset, yOffset) transform.concat() # store the current drawing rect w, h = self.bounds().size w *= self._inverseScale h *= self._inverseScale justInCaseBuffer = 1 * self._inverseScale xOffset += justInCaseBuffer yOffset += justInCaseBuffer w += justInCaseBuffer * 2 h += justInCaseBuffer * 2 self._drawingRect = ((-xOffset, -yOffset), (w, h)) # gather the layers layerSet = self._glyph.layerSet if layerSet is None: layers = [(self._glyph, None)] else: glyphName = self._glyph.name layers = [] for layerName in reversed(layerSet.layerOrder): layer = layerSet[layerName] if glyphName not in layer: continue glyph = layer[glyphName] if glyph == self._glyph: layerName = None layers.append((glyph, layerName)) for glyph, layerName in layers: # draw the image if self.getDrawingAttribute_layerName_("showGlyphImage", layerName): self.drawImage(glyph, layerName) # draw the blues if layerName is None and self.getDrawingAttribute_layerName_("showFontPostscriptBlues", None): self.drawBlues(glyph, layerName) if layerName is None and self.getDrawingAttribute_layerName_("showFontPostscriptFamilyBlues", None): self.drawFamilyBlues(glyph, layerName) # draw the margins if self.getDrawingAttribute_layerName_("showGlyphMargins", layerName): self.drawMargins(glyph, layerName) # draw the vertical metrics if layerName is None and self.getDrawingAttribute_layerName_("showFontVerticalMetrics", None): self.drawVerticalMetrics(glyph, layerName) # draw the glyph if self.getDrawingAttribute_layerName_("showGlyphFill", layerName) or self.getDrawingAttribute_layerName_("showGlyphStroke", layerName): self.drawFillAndStroke(glyph, layerName) if self.getDrawingAttribute_layerName_("showGlyphOnCurvePoints", layerName) or self.getDrawingAttribute_layerName_("showGlyphOffCurvePoints", layerName): self.drawPoints(glyph, layerName) if self.getDrawingAttribute_layerName_("showGlyphAnchors", layerName): self.drawAnchors(glyph, layerName)
def rotateByDegrees_(self, rotation): matrix = NSAffineTransform.transform() matrix.rotateByDegrees_(rotation) self.transformUsingAffineTransform_(matrix)
def translateXBy_yBy_(self, x, y): matrix = NSAffineTransform.transform() matrix.translateXBy_yBy_(x,y) self.transformUsingAffineTransform_(matrix)
def drawRect_(self, rect): # self._layer.drawInFrame_(bounds) # used in Georgs GlyphView try: bounds = self.bounds() NSColor.textBackgroundColor().set() NSRectFill(bounds) scaleFactor = self._scaleFactor thisGlyph = self._layer.parent layerWidth = self._layer.width * scaleFactor descender = self._layer.glyphMetrics()[3] * scaleFactor ascender = self._layer.glyphMetrics()[1] * scaleFactor ## This order is important! Wont work the other way around. bezierPathOnly = self._layer.bezierPath # Path Only if bezierPathOnly is not None: bezierPathOnly = bezierPathOnly.copy() bezierPathWithComponents = self._layer.completeBezierPath # Path & Components bezierPathOpenWithComponents = self._layer.completeOpenBezierPath # Path & Components # Set the scale #-------------- scale = NSAffineTransform.transform() scale.translateXBy_yBy_((bounds.size.width - layerWidth) / 2.0, (bounds.size.height - ascender + descender) / 2.0 - descender) scale.scaleBy_(scaleFactor) # Draw only path in black #------------------------ if thisGlyph.export: pathColor = NSColor.textColor() componentColor = NSColor.secondaryLabelColor() else: pathColor = NSColor.orangeColor() componentColor = NSColor.orangeColor() if bezierPathWithComponents: bezierPathWithComponents.transformUsingAffineTransform_(scale) componentColor.set() # Draw components in gray bezierPathWithComponents.fill() if bezierPathOnly: pathColor.set() bezierPathOnly.transformUsingAffineTransform_(scale) bezierPathOnly.fill() if bezierPathOpenWithComponents: pathColor.set() bezierPathOpenWithComponents.transformUsingAffineTransform_(scale) bezierPathOpenWithComponents.stroke() # Draw non-exported glyphs in orange #----------------------------------- else: NSColor.orangeColor().set() bezierPathWithComponents.transformUsingAffineTransform_(scale) bezierPathWithComponents.fill() attributes = {} attributes[NSFontAttributeName] = NSFont.systemFontOfSize_(14) attributes[NSForegroundColorAttributeName] = NSColor.secondaryLabelColor() thisLKG = thisGlyph.leftKerningGroup thisRKG = thisGlyph.rightKerningGroup if thisLKG is not None: String = NSAttributedString.alloc().initWithString_attributes_(thisLKG, attributes) String.drawAtPoint_alignment_((12, 5), 0) if thisRKG is not None: String = NSAttributedString.alloc().initWithString_attributes_(thisRKG, attributes) String.drawAtPoint_alignment_((bounds.size.width - 12, 5), 2) # AUTO-WIDTH LABEL #----------------- if self._layer.hasAlignedWidth(): attributes[NSForegroundColorAttributeName] = NSColor.lightGrayColor() attributes[NSFontAttributeName] = NSFont.systemFontOfSize_(11) String = NSAttributedString.alloc().initWithString_attributes_("Auto-Width", attributes) String.drawAtPoint_alignment_((bounds.size.width / 2.0, 5), 1) except: print(traceback.format_exc())
def rotate(self, rotation): matrix = NSAffineTransform.transform() matrix.rotateByDegrees_(rotation) self._ns_path.transformUsingAffineTransform_(matrix) self.transformstack[-1].append(["rotate", rotation])