Пример #1
0
 def background(self, layer):
     self.layer = layer
     # draw pixels
     if self.data is None:
         return
     NSGraphicsContext.saveGraphicsState()
     NSGraphicsContext.currentContext().setImageInterpolation_(
         NSImageInterpolationNone)
     self.data.drawInRect_(self.rect)
     NSGraphicsContext.restoreGraphicsState()
Пример #2
0
	def drawForegroundWithOptions_(self, options):
		if self.speedpunklib.getPreference('useFader'):
			visibleRect = self.controller.viewPort
			histOriginX = NSMinX(visibleRect) + 10
			histOriginY = NSMaxY(visibleRect) - 10 - self.histHeight
			NSGraphicsContext.currentContext().saveGraphicsState()
			clippingPath = NSBezierPath.bezierPathWithRoundedRect_cornerRadius_(NSRect((histOriginX, histOriginY), (self.histWidth, self.histHeight)), 5)
			clippingPath.addClip()
			self.speedpunklib.drawGradient(histOriginX, histOriginY, self.histWidth, self.histHeight)
			self.speedpunklib.drawHistogram(histOriginX, histOriginY, self.histWidth, self.histHeight)
			NSGraphicsContext.currentContext().restoreGraphicsState()
Пример #3
0
    def background(self, layer):

        # Check if the drawing should be shown

        currentController = self.controller.view().window().windowController()
        if currentController:
            tool = currentController.toolDrawDelegate()
            if tool.isKindOfClass_(NSClassFromString("GlyphsToolText")) \
                    or tool.isKindOfClass_(NSClassFromString("GlyphsToolHand")) \
                    or tool.isKindOfClass_(NSClassFromString("ScrawlTool")):
                return

        # draw pixels

        data = layer.userData["%s.data" % plugin_id]
        if data is None:
            return
        try:
            data = NSImage.alloc().initWithData_(data)
        except:
            print("Error in image data of layer %s" % layer)
            return

        rect = layer.userData["%s.rect" % plugin_id]
        if rect is None:
            # The drawing rect was not stored in user data.
            # Deduce it from the layer/font metrics.
            font = layer.parent.parent
            pad = int(round(font.upm / 10))

            # find master for image positioning (descender)

            try:
                descender = layer.parent.parent.masters[
                    layer.layerId].descender
            except KeyError:
                descender = int(round(font.upm / 5))

            rect = NSMakeRect(-pad, descender - pad, 2 * pad + layer.width,
                              2 * pad + font.upm)
        else:
            # Use the rect from user data
            rect = NSMakeRect(*rect)
        NSGraphicsContext.saveGraphicsState()
        NSGraphicsContext.currentContext().setImageInterpolation_(
            NSImageInterpolationNone)
        if len(layer.paths) == 0:
            data.drawInRect_(rect)
        else:
            data.drawInRect_fromRect_operation_fraction_(
                rect, NSZeroRect, NSCompositeSourceOver, 0.2)
        NSGraphicsContext.restoreGraphicsState()
Пример #4
0
    def setPixel(self, event, dragging=False):
        if self.data is None:
            return False
        try:
            editView = self.editViewController().graphicView()
        except:
            return False

        layer = editView.activeLayer()
        try:
            master = layer.parent.parent.masters[layer.layerId]
        except KeyError:
            return False
        if master is None:
            return False

        # Get location of click in font coordinates
        Loc = editView.getActiveLocation_(event)
        loc_pixel = ((Loc.x - self.rect.origin.x) / self.pixel_size,
                     (Loc.y - self.rect.origin.y) / self.pixel_size /
                     self.pixel_ratio)
        if self.prev_location != loc_pixel:
            x, y = loc_pixel
            current = NSGraphicsContext.currentContext()
            context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(
                self.data)
            if context is None:
                self.prev_location = loc_pixel
                print("Could not get context in setPixel")
                return False
            NSGraphicsContext.saveGraphicsState()
            NSGraphicsContext.setCurrentContext_(context)
            if self.erase:
                NSColor.whiteColor().set()
            else:
                NSColor.blackColor().set()
            effective_size = self.pen_size / self.pixel_size
            if dragging and self.prev_location is not None:
                px, py = self.prev_location
                path = NSBezierPath.alloc().init()
                path.setLineCapStyle_(NSRoundLineCapStyle)
                path.setLineWidth_(effective_size)
                # path.strokeLineFromPoint_toPoint_(x, y, x + self.pen_size, y + self.pen_size)
                path.moveToPoint_((px, py))
                path.lineToPoint_((x, y))
                path.stroke()
                self.needs_save = True
            else:
                half = effective_size / 2
                rect = NSMakeRect(x - half, y - half, effective_size,
                                  effective_size)
                path = NSBezierPath.bezierPathWithOvalInRect_(rect)
                path.fill()
                self.needs_save = True
            # For rectangular pens:
            # NSBezierPath.fillRect_(rect)
            NSGraphicsContext.setCurrentContext_(current)
            NSGraphicsContext.restoreGraphicsState()
            self.prev_location = loc_pixel
        return True
Пример #5
0
def save_graphics_state():
    context = NSGraphicsContext.currentContext()
    context.saveGraphicsState()
    try:
        yield context
    finally:
        context.restoreGraphicsState()
Пример #6
0
	def generateThumbnail(self):
		if not self._thumbnail:
			if usePyObjC:
				from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext, NSCompositeCopy, NSImage
				from Foundation import NSRect
				image = self.image
				rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
					None,
					int(self.thumbnailSize), int(self.thumbnailSize),
					8, 4,
					True,
					False,
					NSCalibratedRGBColorSpace,
					0, 32,
				)
				context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)
				oldContext = NSGraphicsContext.currentContext()
				NSGraphicsContext.setCurrentContext_(context)
				image.drawInRect_fromRect_operation_fraction_(
					NSRect((0, 0), (self.thumbnailSize, self.thumbnailSize)),
					NSRect((0, 0), image.size()),
					NSCompositeCopy,
					1.0,
				)
				NSGraphicsContext.setCurrentContext_(oldContext)
				self._thumbnail = NSImage.alloc().initWithSize_((self.thumbnailSize, self.thumbnailSize))
				self._thumbnail.addRepresentation_(rep)
			else:
				import wx
				try:
					image = self.image.Scale(self.thumbnailSize, self.thumbnailSize, wx.IMAGE_QUALITY_HIGH)
				except AttributeError: # wx 2.6 can't do IMAGE_QUALITY_HIGH
					image = self.image.Scale(self.thumbnailSize, self.thumbnailSize)
				self._thumbnail = wx.BitmapFromImage(image)
		return self._thumbnail
Пример #7
0
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()
Пример #8
0
 def erase(self):
     ns = self._ns_path
     self._backcolor._ns_color.set()
     ctx = NSGraphicsContext.currentContext()
     ctx.setCompositingOperation_(NSCompositeCopy)
     ns.fill()
     ctx.setCompositingOperation_(NSCompositeSourceOver)
Пример #9
0
 def erase(self):
     ns = self._ns_path
     self._backcolor._ns_color.set()
     ctx = NSGraphicsContext.currentContext()
     ctx.setCompositingOperation_(NSCompositeCopy)
     ns.fill()
     ctx.setCompositingOperation_(NSCompositeSourceOver)
Пример #10
0
 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()
Пример #11
0
 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()
Пример #12
0
    def draw(self, colorPalette, defaultColor):
        from blackrenderer.backends.coregraphics import CoreGraphicsCanvas

        cgContext = NSGraphicsContext.currentContext().CGContext()
        self.colorFont.drawGlyph(
            self.glyphName,
            CoreGraphicsCanvas(cgContext),
            palette=colorPalette,
            textColor=defaultColor,
        )
Пример #13
0
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()
Пример #14
0
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()
Пример #15
0
def drawGlyphAnchors(glyph,
                     scale,
                     rect,
                     drawAnchor=True,
                     drawText=True,
                     color=None,
                     textColor=None,
                     backgroundColor=None,
                     flipped=False):
    if not glyph.anchors:
        return
    if color is None:
        color = getDefaultColor("glyphAnchor")
    fallbackColor = color
    if backgroundColor is None:
        backgroundColor = getDefaultColor("background")
    anchorSize = 5 * scale
    anchorHalfSize = anchorSize / 2
    for anchor in glyph.anchors:
        if anchor.color is not None:
            color = colorToNSColor(anchor.color)
        else:
            color = fallbackColor
        x = anchor.x
        y = anchor.y
        name = anchor.name
        context = NSGraphicsContext.currentContext()
        context.saveGraphicsState()
        #shadow = NSShadow.alloc().init()
        #shadow.setShadowColor_(backgroundColor)
        #shadow.setShadowOffset_((0, 0))
        #shadow.setShadowBlurRadius_(3)
        #shadow.set()
        if drawAnchor:
            r = ((x - anchorHalfSize, y - anchorHalfSize), (anchorSize,
                                                            anchorSize))
            color.set()
            drawFilledOval(r)
        if drawText and name:
            attributes = {
                NSFontAttributeName: NSFont.boldSystemFontOfSize_(12),
                NSForegroundColorAttributeName: textColor,
            }
            y += 25 * scale
            drawTextAtPoint(name, (x, y),
                            scale,
                            attributes,
                            xAlign="center",
                            yAlign="top",
                            flipped=flipped)
        context.restoreGraphicsState()
Пример #16
0
 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
Пример #17
0
 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
Пример #18
0
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)
Пример #19
0
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)
Пример #20
0
	def toRGBA(self):
		if usePyObjC:
			from AppKit import NSBitmapImageRep, NSDeviceRGBColorSpace, NSGraphicsContext, NSCompositeCopy
			from Foundation import NSRect
			image = self.image
			size = image.size()
			rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
				None,
				int(size.width), int(size.height),
				8, 4,
				True,
				False,
				NSDeviceRGBColorSpace,
				0, 32,
			)
			context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)
			oldContext = NSGraphicsContext.currentContext()
			NSGraphicsContext.setCurrentContext_(context)
			oldFlipped = image.isFlipped()
			image.setFlipped_(True)
			image.drawInRect_fromRect_operation_fraction_(
				NSRect((0, 0), size),
				NSRect((0, 0), size),
				NSCompositeCopy,
				1.0,
			)
			image.setFlipped_(oldFlipped)
			NSGraphicsContext.setCurrentContext_(oldContext)
			# FIXME: take bytesPerRow into account
			data = str(rep.bitmapData())
		else:
			image = self.image.Mirror(horizontally = False) # wxImage coordinates are flipped vertically
			data = list(image.GetData())
			rdata = data[0::3]
			gdata = data[1::3]
			bdata = data[2::3]
			if image.HasAlpha():
				adata = image.GetAlpha()
			else:
				adata = '\xFF' * len(rdata)
			data = ''.join([r + g + b + a for r, g, b, a in zip(rdata, gdata, bdata, adata)])
		return data
Пример #21
0
async def test_colrV1Font():
    fontPath = getFontPath("more_samples-glyf_colr_1.ttf")
    numFonts, opener, getSortInfo = getOpener(fontPath)
    font = opener(fontPath, 0)
    await font.load(None)
    textInfo = TextInfo("c")
    glyphs = font.getGlyphRunFromTextInfo(textInfo)
    glyphNames = [g.name for g in glyphs]
    glyphDrawing, *_ = font.getGlyphDrawings(glyphNames, True)
    boundingBox = glyphDrawing.bounds
    assert (100, 0, 900, 1000) == boundingBox
    surface = CoreGraphicsPixelSurface(boundingBox)
    context = NSGraphicsContext.graphicsContextWithCGContext_flipped_(
        surface.context, False)
    savedContext = NSGraphicsContext.currentContext()
    try:
        NSGraphicsContext.setCurrentContext_(context)
        glyphDrawing.draw(glyphs.colorPalette, (0, 0, 0, 1))
    finally:
        NSGraphicsContext.setCurrentContext_(savedContext)
Пример #22
0
def NSImageFactory(image):
    font = image.font
    if font is None:
        return
    layer = image.layer
    images = font.images
    if image.fileName not in images:
        return None
    imageColor = image.color
    if imageColor is None:
        imageColor = layer.color
    data = images[image.fileName]
    data = NSData.dataWithBytes_length_(data, len(data))
    if imageColor is None:
        return NSImage.alloc().initWithData_(data)
    # make the input image
    inputImage = CIImage.imageWithData_(data)
    # make a color filter
    r, g, b, a = imageColor
    color0 = CIColor.colorWithRed_green_blue_(r, g, b)
    color1 = CIColor.colorWithRed_green_blue_(1, 1, 1)
    falseColorFilter = CIFilter.filterWithName_("CIFalseColor")
    falseColorFilter.setValue_forKey_(inputImage, "inputImage")
    falseColorFilter.setValue_forKey_(color0, "inputColor0")
    falseColorFilter.setValue_forKey_(color1, "inputColor1")
    # get the result
    ciImage = falseColorFilter.valueForKey_("outputImage")
    # make an NSImage
    nsImage = NSImage.alloc().initWithSize_(ciImage.extent().size)
    nsImage.lockFocus()
    context = NSGraphicsContext.currentContext().CIContext()
    context.drawImage_atPoint_fromRect_(ciImage, (0, 0), ciImage.extent())
    nsImage.unlockFocus()
    # apply the alpha
    finalImage = NSImage.alloc().initWithSize_(nsImage.size())
    finalImage.lockFocus()
    nsImage.drawAtPoint_fromRect_operation_fraction_(
        (0, 0), ((0, 0), nsImage.size()), NSCompositeSourceOver, a
    )
    finalImage.unlockFocus()
    return finalImage
Пример #23
0
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()
Пример #24
0
def initImage(layer, width, height, pixel_size=default_pixel_size, ratio=1):
    # See https://developer.apple.com/documentation/appkit/nsbitmapimagerep/1395538-init
    img = NSBitmapImageRep.alloc(
    ).initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_(
        None,  # BitmapDataPlanes
        int(round(width / pixel_size)),  # pixelsWide
        int(round(height / pixel_size / ratio)),  # pixelsHigh
        8,  # bitsPerSample: 1, 2, 4, 8, 12, or 16
        1,  # samplesPerPixel: 1 - 5
        False,  # hasAlpha
        False,  # isPlanar
        NSDeviceWhiteColorSpace,  # colorSpaceName
        # NSDeviceRGBColorSpace,
        0,  # bitmapFormat
        0,  # bytesPerRow
        0,  # bitsPerPixel
    )
    """
        NSCalibratedWhiteColorSpace
        NSCalibratedBlackColorSpace
        NSCalibratedRGBColorSpace
        NSDeviceWhiteColorSpace
        NSDeviceBlackColorSpace
        NSDeviceRGBColorSpace
        NSDeviceCMYKColorSpace
        NSNamedColorSpace
        NSCustomColorSpace
    """
    # The image is filled black for some reason, make it white
    current = NSGraphicsContext.currentContext()
    context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(img)
    NSGraphicsContext.setCurrentContext_(context)
    NSColor.whiteColor().set()
    # NSBezierPath.setLineWidth_(1)
    NSBezierPath.fillRect_(NSMakeRect(0, 0, width, int(round(height / ratio))))
    NSGraphicsContext.setCurrentContext_(current)
    return img
Пример #25
0
def drawGlyphAnchors(glyph, scale, rect, drawAnchor=True, drawText=True, color=None, backgroundColor=None, flipped=False):
    if not glyph.anchors:
        return
    if color is None:
        color = getDefaultColor("glyphAnchor")
    fallbackColor = color
    if backgroundColor is None:
        backgroundColor = getDefaultColor("background")
    anchorSize = 5 * scale
    anchorHalfSize = anchorSize / 2
    for anchor in glyph.anchors:
        if anchor.color is not None:
            color = colorToNSColor(anchor.color)
        else:
            color = fallbackColor
        x = anchor.x
        y = anchor.y
        name = anchor.name
        context = NSGraphicsContext.currentContext()
        context.saveGraphicsState()
        shadow = NSShadow.alloc().init()
        shadow.setShadowColor_(backgroundColor)
        shadow.setShadowOffset_((0, 0))
        shadow.setShadowBlurRadius_(3)
        shadow.set()
        if drawAnchor:
            r = ((x - anchorHalfSize, y - anchorHalfSize), (anchorSize, anchorSize))
            color.set()
            drawFilledOval(r)
        if drawText and name:
            attributes = {
                NSFontAttributeName: NSFont.systemFontOfSize_(9),
                NSForegroundColorAttributeName: color,
            }
            y -= 2 * scale
            drawTextAtPoint(name, (x, y), scale, attributes, xAlign="center", yAlign="top", flipped=flipped)
        context.restoreGraphicsState()
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
Пример #27
0
 def drawRect_(self, dirtyRect):
   context = NSGraphicsContext.currentContext().CGContext()
   Quartz.CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0)
   Quartz.CGContextFillRect(context, dirtyRect)
Пример #28
0
 def grestore(self):
     (self._pencolor, self._fillcolor, self._textcolor, self._backcolor,
         self._pensize, self._font) = self._stack.pop()
     self.transformstack.pop()
     NSGraphicsContext.currentContext().restoreGraphicsState()
Пример #29
0
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
Пример #30
0
 def drawRect_(self, rect):
     super(BackgroundView, self).drawRect_(rect)
     NSGraphicsContext.currentContext().CIContext().drawImage_atPoint_fromRect_(self.outputGradient2, (0, 0), NSRect((0, 0), (WIDTH, BASE_HEIGHT)))
Пример #31
0
 def gsave(self):
     self._stack.append((self._pencolor, self._fillcolor, self._textcolor,
                         self._backcolor, self._pensize, self._font))
     NSGraphicsContext.currentContext().saveGraphicsState()
Пример #32
0
def restore():
	# restore the current graphic state 
	NSGraphicsContext.currentContext().restoreGraphicsState()
Пример #33
0
 def drawRect_(self, dirtyRect):
     context = NSGraphicsContext.currentContext().CGContext()
     Quartz.CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0)
     Quartz.CGContextFillRect(context, dirtyRect)
Пример #34
0
 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()
Пример #35
0
def restore():
    # restore the current graphic state
    NSGraphicsContext.currentContext().restoreGraphicsState()
Пример #36
0
 def drawRect_(self, rect):
     cictx = NSGraphicsContext.currentContext().CIContext()
     cictx.drawImage_atPoint_fromRect_(self.outputGradient1, (0, self.BASE_HEIGHT), NSRect((0, 0), (self.WIDTH, self.BASE_HEIGHT * 4)))
     cictx.drawImage_atPoint_fromRect_(self.outputGradient2, (0, 0), NSRect((0, 0), (self.WIDTH, self.BASE_HEIGHT)))
     super(_SickView, self).drawRect_(rect)
Пример #37
0
def drawFilledRect(rect):
    context = NSGraphicsContext.currentContext()
    context.setShouldAntialias_(False)
    NSRectFillUsingOperation(rect, NSCompositeSourceOver)
    context.setShouldAntialias_(True)
Пример #38
0
	def generateImage(self):
		size = self.imageSize
		dx, dy = self.dx, self.dy
		image = self.texture.image
		if usePyObjC:
			from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext, NSCompositeCopy, NSImage
			from Foundation import NSRect
			rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
				None,
				int(size), int(size),
				8, 4,
				True,
				False,
				NSCalibratedRGBColorSpace,
				0, 32,
			)
			context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)
			oldContext = NSGraphicsContext.currentContext()
			NSGraphicsContext.setCurrentContext_(context)
			image.drawInRect_fromRect_operation_fraction_(
				NSRect((0, 0), (size, size)),
				NSRect((0, 0), image.size()),
				NSCompositeCopy,
				1.0,
			)
			NSGraphicsContext.setCurrentContext_(oldContext)
			image = NSImage.alloc().initWithSize_((size, size))
			image.addRepresentation_(rep)
			rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
				None,
				int(size), int(size),
				8, 4,
				True,
				False,
				NSCalibratedRGBColorSpace,
				0, 32,
			)
			context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)
			oldContext = NSGraphicsContext.currentContext()
			NSGraphicsContext.setCurrentContext_(context)
			srcPoints = (
				(0, 0),
				(size - dx, 0),
				(0, size - dy),
				(size - dx, size - dy),
			)
			dstPoints = (
				(dx, dy),
				(0, dy),
				(dx, 0),
				(0, 0),
			)
			sizes = (
				(size - dx, size - dy),
				(dx, size - dy),
				(size - dx, dy),
				(dx, dy),
			)
			for src, dst, siz in zip(srcPoints, dstPoints, sizes):
				if siz[0] > 0 and siz[1] > 0: # not sure if Cocoa appreciates trying to draw an image with invalid bounds
					image.drawInRect_fromRect_operation_fraction_(
						NSRect(dst, siz),
						NSRect(src, siz),
						NSCompositeCopy,
						1.0,
					)
			NSGraphicsContext.setCurrentContext_(oldContext)
			result = NSImage.alloc().initWithSize_((size, size))
			result.addRepresentation_(rep)
		else:
			import wx
			try:
				image = image.Scale(size, size, wx.IMAGE_QUALITY_HIGH)
			except AttributeError: # wx 2.6 can't do IMAGE_QUALITY_HIGH
				image = image.Scale(size, size)
			result = wx.BitmapFromImage(image)
		return result
Пример #39
0
def save():
    # save the current graphic state
    NSGraphicsContext.currentContext().saveGraphicsState()
Пример #40
0
def save():
	# save the current graphic state 
	NSGraphicsContext.currentContext().saveGraphicsState()
Пример #41
0
    NSRectFillUsingOperation(rect, NSCompositeSourceOver)
    context.setShouldAntialias_(True)


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":
Пример #42
0
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
Пример #43
0
def drawFilledRect(rect):
    context = NSGraphicsContext.currentContext()
    context.setShouldAntialias_(False)
    NSRectFillUsingOperation(rect, NSCompositeSourceOver)
    context.setShouldAntialias_(True)
Пример #44
0
 def grestore(self):
     (self._pencolor, self._fillcolor, self._textcolor, self._backcolor,
      self._pensize, self._font) = self._stack.pop()
     NSGraphicsContext.currentContext().restoreGraphicsState()
Пример #45
0
 def gsave(self):
     self._stack.append((
         self._pencolor, self._fillcolor, self._textcolor, self._backcolor,
         self._pensize, self._font))
     self.transformstack.append([])
     NSGraphicsContext.currentContext().saveGraphicsState()
Пример #46
0
 def drawRect_(self, rect):
     NSColor.whiteColor().set()
     NSBezierPath.bezierPathWithRect_(NSRect((0, 0), self.frame().size)).fill()
     NSGraphicsContext.currentContext().CIContext().drawImage_atPoint_fromRect_(self._filter.valueForKey_('outputImage'), (0, 0), self.image.extent())
Пример #47
0
 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()