本文整理汇总了Python中AppKit.NSImage.alloc方法的典型用法代码示例。如果您正苦于以下问题:Python NSImage.alloc方法的具体用法?Python NSImage.alloc怎么用?Python NSImage.alloc使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类AppKit.NSImage
的用法示例。
在下文中一共展示了NSImage.alloc方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _pyobjc_notify
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def _pyobjc_notify(message, title=None, subtitle=None, appIcon=None, contentImage=None, open_URL=None, delay=0, sound=False):
swizzle(objc.lookUpClass('NSBundle'),
b'bundleIdentifier',
swizzled_bundleIdentifier)
notification = NSUserNotification.alloc().init()
notification.setInformativeText_(message)
if title:
notification.setTitle_(title)
if subtitle:
notification.setSubtitle_(subtitle)
if appIcon:
url = NSURL.alloc().initWithString_(appIcon)
image = NSImage.alloc().initWithContentsOfURL_(url)
notification.set_identityImage_(image)
if contentImage:
url = NSURL.alloc().initWithString_(contentImage)
image = NSImage.alloc().initWithContentsOfURL_(url)
notification.setContentImage_(image)
if sound:
notification.setSoundName_(
"NSUserNotificationDefaultSoundName")
notification.setDeliveryDate_(
NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date()))
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(
notification)
示例2: applicationDidFinishLaunching_
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def applicationDidFinishLaunching_(self, notification):
self.noDevice = None
#Create menu
self.menu = NSMenu.alloc().init()
self.barItem = dict()
# Load images
self.noDeviceImage = NSImage.alloc().initByReferencingFile_('icons/no_device.png')
self.barImage = dict(kb = NSImage.alloc().initByReferencingFile_('icons/kb.png'),
magicMouse = NSImage.alloc().initByReferencingFile_('icons/magic_mouse.png'),
mightyMouse = NSImage.alloc().initByReferencingFile_('icons/mighty_mouse.png'),
magicTrackpad = NSImage.alloc().initByReferencingFile_('icons/TrackpadIcon.png'))
#Define menu items
self.statusbar = NSStatusBar.systemStatusBar()
self.menuAbout = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('About BtBatStat', 'about:', '')
self.separator_menu_item = NSMenuItem.separatorItem()
self.menuQuit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
# Get the timer going
self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 10.0, self, 'tick:', None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
self.timer.fire()
#Add menu items
self.menu.addItem_(self.menuAbout)
self.menu.addItem_(self.separator_menu_item)
self.menu.addItem_(self.menuQuit)
#Check for updates
checkForUpdates()
示例3: __init__
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def __init__(self, posSize, segmentDescriptions, callback=None, selectionStyle="one", sizeStyle="small"):
self._setupView(self.nsSegmentedControlClass, posSize)
if self.nsSegmentedCellClass != NSSegmentedCell:
self._nsObject.setCell_(self.nsSegmentedCellClass.alloc().init())
if callback is not None:
self._setCallback(callback)
self._setSizeStyle(sizeStyle)
nsObject = self._nsObject
nsObject.setSegmentCount_(len(segmentDescriptions))
nsObject.cell().setTrackingMode_(_trackingModeMap[selectionStyle])
for segmentIndex, segmentDescription in enumerate(segmentDescriptions):
width = segmentDescription.get("width", 0)
title = segmentDescription.get("title", "")
enabled = segmentDescription.get("enabled", True)
imagePath = segmentDescription.get("imagePath")
imageNamed = segmentDescription.get("imageNamed")
imageTemplate = segmentDescription.get("imageTemplate")
imageObject = segmentDescription.get("imageObject")
# create the NSImage if needed
if imagePath is not None:
image = NSImage.alloc().initWithContentsOfFile_(imagePath)
elif imageNamed is not None:
image = NSImage.imageNamed_(imageNamed)
elif imageObject is not None:
image = imageObject
else:
image = None
nsObject.setWidth_forSegment_(width, segmentIndex)
nsObject.setLabel_forSegment_(title, segmentIndex)
nsObject.setEnabled_forSegment_(enabled, segmentIndex)
if image is not None:
if imageTemplate is not None:
# only change the image template setting if its either True or False
image.setTemplate_(imageTemplate)
nsObject.setImage_forSegment_(image, segmentIndex)
示例4: MenuImageRepresentationFactory
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
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
示例5: movie_maker
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def movie_maker(movdir,imgdir,timeval,timescale,ih):
print('making movie %s' % ih)
imgpaths = glob.glob(os.path.join(imgdir,'ocean_his_*_%s.png'%ih))
imgpaths.sort()
movpath = os.path.join(movdir,'%s.mov' %ih )
'''I am creating a new image sequence (QuickTime movie).'''
mov, err = QTMovie.alloc().initToWritableFile_error_(movpath, None)
if mov == None:
errmsg = 'Could not create movie file: %s' % (movpath)
raise IOError, errmsg
duration = QTMakeTime(timeval, timescale)
# you can also use "tiff"
# attrs = {QTAddImageCodecType: 'avc1'}#, QTAddImageCodecQuality: codecHighQuality}
attrs = {QTAddImageCodecType: 'avc1'}
for imgpath in imgpaths:
# img = NSImage.alloc().initWithContentsOfFile_(imgpath)
img = NSImage.alloc().initByReferencingFile_(imgpath)
mov.addImage_forDuration_withAttributes_(img, duration, attrs)
del(img)
print('Writing movie %s' %ih)
mov.updateMovieFile()
示例6: send_OS_X_notify
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def send_OS_X_notify(title, content, img_path):
'''发送Mac桌面通知'''
def swizzle(cls, SEL, func):
old_IMP = cls.instanceMethodForSelector_(SEL)
def wrapper(self, *args, **kwargs):
return func(self, old_IMP, *args, **kwargs)
new_IMP = objc.selector(wrapper, selector=old_IMP.selector,
signature=old_IMP.signature)
objc.classAddMethod(cls, SEL, new_IMP)
def swizzled_bundleIdentifier(self, original):
# Use iTunes icon for notification
return 'com.apple.itunes'
swizzle(objc.lookUpClass('NSBundle'),
b'bundleIdentifier',
swizzled_bundleIdentifier)
notification = NSUserNotification.alloc().init()
notification.setInformativeText_('')
notification.setTitle_(title.decode('utf-8'))
notification.setSubtitle_(content.decode('utf-8'))
notification.setInformativeText_('')
notification.setUserInfo_({})
if img_path is not None:
image = NSImage.alloc().initWithContentsOfFile_(img_path)
# notification.setContentImage_(image)
notification.set_identityImage_(image)
notification.setDeliveryDate_(
NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date())
)
NSUserNotificationCenter.defaultUserNotificationCenter().\
scheduleNotification_(notification)
示例7: init
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def init():
print "init ui cocoa"
global browserwindow
app = NSApplication.sharedApplication()
app.setActivationPolicy_(1)
start_taskbar()
app.finishLaunching()
_browserwindow = NSWindow.alloc()
icon = NSImage.alloc().initByReferencingFile_(settings.mainicon)
app.setApplicationIconImage_(icon)
deleg = Delegate.alloc()
deleg.init()
app.setDelegate_(deleg)
signal.signal(signal.SIGINT, mac_sigint)
from .input import BrowserDelegate
bd = BrowserDelegate.alloc()
bd.init()
browserwindow = draw_browser(_browserwindow, bd)
from .... import ui
ui.log.debug('using cocoa')
atexit.register(exit)
gevent_timer(deleg)
ui.module_initialized.set()
sys.exit = exit
AppHelper.runEventLoop()
示例8: add
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def add(self, canvas_or_context):
if self.movie is None:
# The first frame will be written to a temporary png file,
# then opened as a movie file, then saved again as a movie.
handle, self.tmpfname = mkstemp(".tiff")
canvas_or_context.save(self.tmpfname)
try:
movie, err = QTMovie.movieWithFile_error_(self.tmpfname, None)
movie.setAttribute_forKey_(NSNumber.numberWithBool_(True), QTMovieEditableAttribute)
range = QTMakeTimeRange(QTMakeTime(0, 600), movie.duration())
movie.scaleSegment_newDuration_(range, self._time)
if err is not None:
raise str(err)
movie.writeToFile_withAttributes_(self.fname, {QTMovieFlatten: True})
self.movie, err = QTMovie.movieWithFile_error_(self.fname, None)
self.movie.setAttribute_forKey_(NSNumber.numberWithBool_(True), QTMovieEditableAttribute)
if err is not None:
raise str(err)
self.imageTrack = self.movie.tracks()[0]
finally:
os.remove(self.tmpfname)
else:
try:
canvas_or_context.save(self.tmpfname)
img = NSImage.alloc().initByReferencingFile_(self.tmpfname)
self.imageTrack.addImage_forDuration_withAttributes_(img, self._time, {QTAddImageCodecType: "tiff"})
finally:
try:
os.remove(self.tmpfname)
except OSError:
pass
self.frame += 1
示例9: setupUI
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def setupUI(self):
self.statusbar = NSStatusBar.systemStatusBar()
self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength) #NSSquareStatusItemLength #NSVariableStatusItemLength
# Set initial image icon
icon_path = os.path.join(current_path, "../trayicon.ico")
image = NSImage.alloc().initByReferencingFile_(icon_path)
image.setScalesWhenResized_(True)
image.setSize_((20, 20))
self.statusitem.setImage_(image)
# Let it highlight upon clicking
self.statusitem.setHighlightMode_(1)
self.statusitem.setToolTip_("ZeroNet")
# Build a very simple menu
self.menu = NSMenu.alloc().init()
self.menu.setAutoenablesItems_(False)
#self.create_menu_item( 'ip_external', 'IP: %s' % INFO['ip_external'], 'info:')
self.menu.addItem_( NSMenuItem.separatorItem() )
# Links
self.create_menu_item( 'open_zeronet', 'Open ZeroNet', 'open:')
self.create_menu_item( 'open_reddit', 'Zeronet Reddit Community', 'openreddit:')
self.create_menu_item( 'open_gh', 'Report issues/feature requests', 'opengithub:')
self.menu.addItem_( NSMenuItem.separatorItem() )
self.create_menu_item( 'quit_zeronet', 'Quit ZeroNet', 'windowWillClose:' )
# Bind it to the status item and hide dock icon
self.statusitem.setMenu_(self.menu)
NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)
示例10: draw_texture
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def draw_texture(self, texture, location, scale):
''' Draws the texture into this build's graphics context
at the location, to the given scale.
self.render() needs to a call parent of this method, in order
to set up the Cocoa graphics context for the draw calls to work
texture: a Texture object
location: (tx, ty) tuple
scale: (sx, sy) tuple
'''
tx, ty = location
sx, sy = scale
tex = NSImage.alloc().initWithContentsOfFile_(texture.path())
# TODO: support opacity
if (sx != 1 or sy != 1):
#tex = tex.resize((sx, sy))
tex.setSize_(NSSize(sx, sy))
# Cocoa uses inverted Y-axis...
ty_ = self.kpf.height - tex.size().height - ty
tex.drawAtPoint_fromRect_operation_fraction_(NSPoint(tx, ty_), NSZeroRect, NSCompositeSourceOver, 1.0)
示例11: _setup_ui_dialogs
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def _setup_ui_dialogs(self):
# This needs to be here otherwise we can't install the dialog
if 'STOQ_TEST_MODE' in os.environ:
return
log.debug('providing graphical notification dialogs')
from stoqlib.gui.base.dialogs import DialogSystemNotifier
from stoqlib.lib.interfaces import ISystemNotifier
from kiwi.component import provide_utility
provide_utility(ISystemNotifier, DialogSystemNotifier(), replace=True)
import gtk
from kiwi.environ import environ
from kiwi.ui.pixbufutils import pixbuf_from_string
data = environ.get_resource_string(
'stoq', 'pixmaps', 'stoq-stock-app-24x24.png')
gtk.window_set_default_icon(pixbuf_from_string(data))
if platform.system() == 'Darwin':
from AppKit import NSApplication, NSData, NSImage
bytes = environ.get_resource_string(
'stoq', 'pixmaps', 'stoq-stock-app-48x48.png')
data = NSData.alloc().initWithBytes_length_(bytes, len(bytes))
icon = NSImage.alloc().initWithData_(data)
app = NSApplication.sharedApplication()
app.setApplicationIconImage_(icon)
示例12: __init__
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def __init__(self, posSize,
imagePath=None, imageNamed=None, imageObject=None,
title=None, bordered=True, imagePosition="top", callback=None, sizeStyle="regular"):
super(ImageButton, self).__init__(posSize, title=title, callback=callback, sizeStyle=sizeStyle)
image = None
if imagePath is not None:
image = NSImage.alloc().initWithContentsOfFile_(imagePath)
elif imageNamed is not None:
image = NSImage.imageNamed_(imageNamed)
elif imageObject is not None:
image = imageObject
if image is not None:
self._nsObject.setImage_(image)
self._nsObject.setBordered_(bordered)
if title is None:
position = NSImageOnly
else:
position= _imagePositionMap[imagePosition]
if imagePosition == "left":
self._nsObject.setAlignment_(NSRightTextAlignment)
elif imagePosition == "right":
self._nsObject.setAlignment_(NSLeftTextAlignment)
if not bordered:
self._nsObject.cell().setHighlightsBy_(NSNoCellMask)
self._nsObject.setImagePosition_(position)
示例13: draw_texture
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def draw_texture(self, texture, location, scale):
''' Draws the texture into this build's graphics context
at the location, to the given scale.
self.render() needs to a call parent of this method, in order
to set up the Cocoa graphics context for the draw calls to work
texture: a Texture object
location: (tx, ty) tuple
scale: (sx, sy) tuple
'''
tx, ty = location
sx, sy = scale
# Cache all assets so we don't frequently reload our PDFs.
path = texture.path()
if path in Build._asset_cache:
tex = Build._asset_cache[path].copy()
else:
tex = NSImage.alloc().initWithContentsOfFile_(path)
Build._asset_cache[path] = tex.copy()
if isinstance(texture, TextureWithIndex):
rep = tex.representations()[0]
rep.setCurrentPage_(texture.index())
# TODO: support opacity
if (sx != 1 or sy != 1):
#tex = tex.resize((sx, sy))
tex.setSize_(NSSize(sx, sy))
# Cocoa uses inverted Y-axis...
ty_ = self.kpf.height - tex.size().height - ty
tex.drawAtPoint_fromRect_operation_fraction_(NSPoint(tx, ty_), NSZeroRect, NSCompositeSourceOver, 1.0)
示例14: applicationDidFinishLaunching_
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
def applicationDidFinishLaunching_(self, notification):
self.statusbar = NSStatusBar.systemStatusBar()
# Create the statusbar item
self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength)
# Set initial image
raw_data = base64.b64decode(''.join(GOAGENT_ICON_DATA.strip().splitlines()))
self.image_data = NSData.dataWithBytes_length_(raw_data, len(raw_data))
self.image = NSImage.alloc().initWithData_(self.image_data)
self.statusitem.setImage_(self.image)
# Let it highlight upon clicking
self.statusitem.setHighlightMode_(1)
# Set a tooltip
self.statusitem.setToolTip_('GoAgent OSX')
# Build a very simple menu
self.menu = NSMenu.alloc().init()
# Show Menu Item
menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Show', 'show:', '')
self.menu.addItem_(menuitem)
# Hide Menu Item
menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Hide', 'hide:', '')
self.menu.addItem_(menuitem)
# Rest Menu Item
menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Reset', 'reset:', '')
self.menu.addItem_(menuitem)
# Default event
menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
self.menu.addItem_(menuitem)
# Bind it to the status item
self.statusitem.setMenu_(self.menu)
示例15: __init__
# 需要导入模块: from AppKit import NSImage [as 别名]
# 或者: from AppKit.NSImage import alloc [as 别名]
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