Here is a crude working version. The only drawback here is that it doesn't center the glyph on the button but it's not hard to figure out. I decomposed the glyph so I can scale it.
from fontTools.pens.cocoaPen import CocoaPen
from vanilla import *
import AppKit
from mojo.pens import DecomposePointPen
g = CurrentGlyph()
def decomposeGlyph(srcGlyph):
decomposedGlyph = RGlyph()
decomposedGlyph.width = srcGlyph.width
dstPen = decomposedGlyph.getPointPen()
decomposePen = DecomposePointPen(srcGlyph.font, dstPen)
srcGlyph.drawPoints(decomposePen)
return decomposedGlyph
def glyphImage(g, size, margin):
g = decomposeGlyph(g)
bottomX, bottomY, topX, topY = g.bounds
g.moveBy((-bottomX, -bottomY))
w = topX - bottomX
h = topY - bottomY
maxDimensionGlyph = max([w, h])
maxDimensionSize = max([d-(margin*2) for d in size])
scaleFactor = maxDimensionSize / maxDimensionGlyph
g.scaleBy(scaleFactor)
g.moveBy((margin, margin))
pen = CocoaPen(g.layer)
g.draw(pen)
image = AppKit.NSImage.alloc().initWithSize_(size)
image.lockFocus()
if AppKit.NSApp().appearance() == AppKit.NSAppearance.appearanceNamed_(AppKit.NSAppearanceNameDarkAqua):
AppKit.NSColor.whiteColor().set()
else:
AppKit.NSColor.blackColor().set()
pen.path.fill()
image.unlockFocus()
return image
class ImageButtonDemo:
def __init__(self):
self.w = Window((1000, 1000))
self.w.button = ImageButton((10, 10, 50, 50), imageObject=glyphImage(g, (50, 50), 10),
callback=self.buttonCallback)
self.w.open()
def buttonCallback(self, sender):
print("button hit!")
ImageButtonDemo()