在Electron中保持窗口比例可以通过设置窗口大小和监听窗口大小变化事件来实现。以下是一个示例代码:
const { app, BrowserWindow } = require('electron');
let mainWindow;
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
minWidth: 400, // 设置最小宽度
minHeight: 300, // 设置最小高度
aspectRatio: 16 / 9, // 设置窗口宽高比例
webPreferences: {
nodeIntegration: true,
},
});
mainWindow.loadFile('index.html');
// 监听窗口大小变化事件
mainWindow.on('resize', () => {
const [width, height] = mainWindow.getSize();
const aspectRatio = 16 / 9; // 设置宽高比例
let newWidth = width;
let newHeight = height;
// 计算调整后的宽度和高度
if (width / height < aspectRatio) {
newWidth = height * aspectRatio;
} else {
newHeight = width / aspectRatio;
}
// 设置新的窗口大小
mainWindow.setSize(newWidth, newHeight);
});
});
在上述代码中,我们在创建BrowserWindow
时设置了初始的宽度和高度,并通过aspectRatio
属性设置了窗口的宽高比例。然后通过监听窗口的resize
事件,在事件回调中计算调整后的宽度和高度,并使用setSize
方法设置新的窗口大小。这样就可以保持窗口的宽高比例不变。
请注意,上述示例代码是基于Electron的主进程编写的,将其放在主进程文件中即可。