Proper tray icon

I've been playing around with tray icon so I thought to write down couple of thoughts.

Not to repeat the code, you can check out how to use it in documentation.
BUT, be aware of couple of things though...

Straight to the point

var platform = require('os').platform();  
var trayImage;  
var imageFolder = __dirname + '/assets/images';

// Determine appropriate icon for platform
if (platform == 'darwin') {  
    trayImage = imageFolder + '/osx/trayTemplate.png';
}
else if (platform == 'win32') {  
    trayImage = imageFolder + '/win/tray.ico';
}
appIcon = new Tray(trayImage);

if (platform == "darwin") {  
    appIcon.setPressedImage(imageFolder + '/osx/trayHighlight.png');
}

Longer version

Create icon

For OS X, create icons:

  • icon.png (for best results aim 16x16px)
  • [email protected] (32x32px)

For Windows, create single icon:

  • icon.ico

ICO format will work better than classic PNG. If you want PNG, make it 32x32px.

Show icon correctly on OS X menu

OS X supports light and dark mode which transforms your menu bar. To cover both scenarios, you can provide template icon which is in fact icon with black and transparent pixels. Those black pixels are dynamically coloured to be harmonious with other icons depending on your selected menu colour mode.

Electron offers to load image immediately as template just by using correct naming convention. You can name you images:

  • iconTemplate.png
  • iconTemplate@2x.png

Or you can make it through code:

const nativeImage = require('electron').nativeImage;  
var image = nativeImage.createFromPath('/Users/somebody/images/icon.png');  
image.setTemplateImage(true);  

Fine tuning for OS X

If you test your app at this point, you'll see your icon and it is going to react fine on changes between light and dark mode. Problem appears when you click it - it will highlight icon, but graphic won't change colour (and it should go become white). To work around this, create same icon but use white instead of black. No need to have Template ending in name:

  • iconHighlight.png
  • [email protected]

Then, using setPressedImage method, define it on your icon:

var appIcon = new Tray('/path/to/iconTemplate.png');  
appIcon.setPressedImage('/path/to/iconHighlight.png');  

That's it!

P.S. You can easily convert your icons on iConvert Icons.

About Vjekoslav Ratkajec

Software developer from Zagreb, Croatia. Love programming, running, hiking and biking. Adore nature and animals. Also author of this blog.

Comments