当前位置: 首页>>代码示例>>Python>>正文


Python AppKit.NSImage类代码示例

本文整理汇总了Python中AppKit.NSImage的典型用法代码示例。如果您正苦于以下问题:Python NSImage类的具体用法?Python NSImage怎么用?Python NSImage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了NSImage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: applicationDidFinishLaunching_

  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()
开发者ID:Ku2f,项目名称:btbatstat,代码行数:33,代码来源:BtBatStat.py

示例2: _pyobjc_notify

            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)
开发者ID:felixonmars,项目名称:pyfm,代码行数:27,代码来源:notifier.py

示例3: __init__

 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)
开发者ID:LettError,项目名称:vanilla,代码行数:25,代码来源:vanillaButton.py

示例4: __init__

 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)
开发者ID:typesupply,项目名称:vanilla,代码行数:35,代码来源:vanillaSegmentedButton.py

示例5: applicationDidFinishLaunching_

    def applicationDidFinishLaunching_(self, notification):
        #activate logging with ToggleProxy -logging 1 
        self.shouldLog = NSUserDefaults.standardUserDefaults().boolForKey_("logging")
        
        # load icon files
        self.active_image = NSImage.imageNamed_("StatusBarImage")
        self.inactive_image = NSImage.imageNamed_("StatusBarImage-inactive")
        self.no_network_image = NSImage.imageNamed_("StatusBarImage-noNetwork")
        self.active_image.setTemplate_(True)
        self.inactive_image.setTemplate_(True)
        self.no_network_image.setTemplate_(True)

        # make status bar item
        self.statusitem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
        self.statusitem.retain()
        self.statusitem.setHighlightMode_(False)
        self.statusitem.setEnabled_(True)

        # insert a menu into the status bar item
        self.menu = NSMenu.alloc().init()
        self.statusitem.setMenu_(self.menu)

        # open connection to the dynamic (configuration) store
        self.store = SCDynamicStoreCreate(None, "name.klep.toggleproxy", self.dynamicStoreCallback, None)
        self.prefDict = SCNetworkProtocolGetConfiguration(SCNetworkServiceCopyProtocol(self.service, kSCNetworkProtocolTypeProxies))
        self.constructMenu()

        self.watchForProxyOrIpChanges()
        self.updateUI()
        self.setEnvVariables()
开发者ID:arnaudruffin,项目名称:OsxProxyToggler,代码行数:30,代码来源:ToggleProxy.py

示例6: _createToolbarItem

    def _createToolbarItem(self, itemData):
        itemIdentifier = itemData.get("itemIdentifier")
        if itemIdentifier is None:
            raise VanillaError("toolbar item data must contain a unique itemIdentifier string")
        if itemIdentifier in self._toolbarItems:
            raise VanillaError("toolbar itemIdentifier is not unique: %r" % itemIdentifier)

        if itemIdentifier not in self._toolbarAllowedItemIdentifiers:
            self._toolbarAllowedItemIdentifiers.append(itemIdentifier)
        if itemData.get("visibleByDefault", True):
            self._toolbarDefaultItemIdentifiers.append(itemIdentifier)

        if itemIdentifier.startswith("NS"):
            # no need to create an actual item for a standard Cocoa toolbar item
            return

        label = itemData.get("label")
        paletteLabel = itemData.get("paletteLabel", label)
        toolTip = itemData.get("toolTip", label)
        imagePath = itemData.get("imagePath")
        imageNamed = itemData.get("imageNamed")
        imageObject = itemData.get("imageObject")
        imageTemplate = itemData.get("imageTemplate")
        view = itemData.get("view")
        callback = itemData.get("callback", None)
        # 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
        toolbarItem = NSToolbarItem.alloc().initWithItemIdentifier_(itemIdentifier)
        toolbarItem.setLabel_(label)
        toolbarItem.setPaletteLabel_(paletteLabel)
        toolbarItem.setToolTip_(toolTip)
        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)
            toolbarItem.setImage_(image)
        elif view is not None:
            toolbarItem.setView_(view)
            toolbarItem.setMinSize_(view.frame().size)
            toolbarItem.setMaxSize_(view.frame().size)
        if callback is not None:
            target = VanillaCallbackWrapper(callback)
            toolbarItem.setTarget_(target)
            toolbarItem.setAction_("action:")
            self._toolbarCallbackWrappers[itemIdentifier] = target
        if itemData.get("selectable", False):
            self._toolbarSelectableItemIdentifiers.append(itemIdentifier)
        self._toolbarItems[itemIdentifier] = toolbarItem
开发者ID:typesupply,项目名称:vanilla,代码行数:55,代码来源:vanillaWindows.py

示例7: movie_maker

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()
开发者ID:HyeonJeongKim,项目名称:tools,代码行数:26,代码来源:make_movie.py

示例8: __init__

 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
开发者ID:rceballos98,项目名称:hapticJacket,代码行数:26,代码来源:Pixmap.py

示例9: MenuImageRepresentationFactory

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
开发者ID:andyclymer,项目名称:defconAppKit,代码行数:27,代码来源:menuImageFactory.py

示例10: draw_texture

    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)
开发者ID:Vjoe,项目名称:kaas,代码行数:35,代码来源:kpfutil.py

示例11: add

 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
开发者ID:joaomesq,项目名称:nodebox-pyobjc,代码行数:32,代码来源:QTSupport.py

示例12: send_OS_X_notify

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)
开发者ID:cckiss,项目名称:douban.fm-1,代码行数:34,代码来源:notification.py

示例13: applicationDidFinishLaunching_

    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)
开发者ID:SkyRaker,项目名称:GoAgentX,代码行数:30,代码来源:goagent-osx.py

示例14: init

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()
开发者ID:Werniman,项目名称:client,代码行数:28,代码来源:app.py

示例15: _setup_ui_dialogs

    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)
开发者ID:LeonamSilva,项目名称:stoq,代码行数:25,代码来源:bootstrap.py


注:本文中的AppKit.NSImage类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。