如何将一个图标添加到Electron应用程序

7
我有一个用于制作win.exe和安装程序的Electron构建文件,但图标不是我自己的。在main.js文件中,我有代码用于附加图标,但只能在createWindow函数内部使其工作。在函数外部,我会得到一个错误消息。虽然我的.exe文件可以运行并且我可以得到我的图标,但执行这个操作时会出现错误;安装程序根本无法工作。我尝试了几个教程,但都没有解决这个问题。
const {app, BrowserWindow, Tray} = require('electron')
const path = require('path')
const url = require('url')

let win

function createWindow () {
  const appIcon = new Tray('icon/app.png')
  win = new BrowserWindow({ width: 1920, height: 1080, icon: 'icon/app.ico' })
  console.log(appIcon, win)
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'app/app.html'),
    protocol: 'file:',
    slashes: true
  }))
  win.on('closed', () => {
    win = null
  })
}

app.on('ready', createWindow)
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

package.json

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "MyApp",
  "private": true,
  "main": "main.js",
  "build": {
    "appID": "myapp",
    "productName": "MyApp",
    "icon": "icon/app.ico"
  },
  "scripts": {
    "start": "electron ." ,
    "package": "",
  },
  "author": "Me",
  "license": "ISC",
  "devDependencies": {
    "electron": "^1.6.1"
  }
}

我不确定接下来该怎么做。

您想替换默认应用程序图标还是特定的其他内容? - xxfast
我想要我的图标替换所有位置的默认图标。 - Tim
你有任何想法为什么 Electron 应用程序在 Windows 平板模式下无法自动启动窗口,但在桌面模式下完美运行? - user8317956
3个回答

7

简单的解决方案

const nativeImage = require('electron').nativeImage;
    var image = nativeImage.createFromPath(__dirname + '/public/img/logo.png'); 
 // where public folder on the root dir

    image.setTemplateImage(true);


 // Create the browser window.
    win = new BrowserWindow({
        width: 1179,
        height: 754,
        backgroundColor: '#ffffff',
        transparent: false,
        icon: image
    })

这对我起作用了,不需要使用 image.setTemplateImage(true); - Hawkeye64
1
在几个地方,它说使用路径字符串就足够了。但只有在我在Ubuntu上使用nativeImage之后才能让它工作。 - MrAn3

2

以下方法适用于我。要在任务栏中显示应用程序图标,您可以在main.js(如果使用typescript则为main.ts)中即时更新图标。

原始答案:Original Answer

win.setIcon(path.join(__dirname, '/src/assets/logo-small.png'));

值得一提的是,__dirname指向与package.json相同的目录。最初的回答。

2

在main.js文件中:

mainWindow = new BrowserWindow({width: 800, height: 600,icon: __dirname + '/icon.ico'});

如果您正在使用electron-builder安装程序,则需要注意以下内容。

  "devDependencies": {
    "electron": "^1.4.15",
    "electron-builder": "^12.3.1"
  },

在根目录下创建一个名为build的文件夹,在该文件夹内添加您的icon.ico图标。

有时需要重新启动Electron或构建应用程序2次。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接