普通方案
在windows/runner/main.cpp中,找到以下代码:
Win32Window::Point origin(0, 0);
Win32Window::Size size(360, 640);
修改成:
//假设我们窗口大小为360*640
UINT windowWidth = 360, windowHeight = 640;
UINT scrWidth, scrHeight, xShaft, yShaft;
//屏幕宽高的分辨率
scrWidth = GetSystemMetrics(SM_CXFULLSCREEN);
scrHeight = GetSystemMetrics(SM_CYFULLSCREEN);
//计算居中时的原点坐标
xShaft = (scrWidth - windowWidth) / 2;
yShaft = (scrHeight - windowHeight) / 2;
//设置窗口原点和宽高
Win32Window::Point origin(xShaft, yShaft);
Win32Window::Size size(windowWidth, windowHeight);
这样程序一运行就能居中显示。
Tips: 该方案只能在屏幕100%的时候有效,如果改为其他比例,会有误差。后期研究。
适配方案
- 同样的,我们在windows/runner/main.cpp中,找到以下代码:
Win32Window::Point origin(0, 0);
Win32Window::Size size(360, 640);
此时的Point的值随意设置。
2.在windows/runner/win32_window.cpp中,找到CreateWindow方法。
HWND window = CreateWindow(
window_class, title.c_str(), WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE,
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
Scale(size.width, scale_factor), Scale(size.height, scale_factor),
nullptr, nullptr, GetModuleHandle(nullptr), this);
改为:
UINT scrWidth = GetSystemMetrics(SM_CXFULLSCREEN);//屏幕宽度
UINT scrHeight = GetSystemMetrics(SM_CYFULLSCREEN);//屏幕高度
UINT windowWidth = Scale(size.width, scale_factor);//缩放后的窗口宽度
UINT windowHeight = Scale(size.height, scale_factor);//缩放后的窗口高度
UINT windowOriginX = (scrWidth - windowWidth) / 2;//窗口原点X坐标
UINT windowOriginY = (scrHeight - windowHeight) / 2;//窗口原点y坐标
HWND window = CreateWindow(
window_class, title.c_str(), WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE,
windowOriginX,windowOriginY,windowWidth,windowHeight,
nullptr, nullptr, GetModuleHandle(nullptr), this);
分析:不管缩放到多少,屏幕的宽高像素都不会发生变化,这时候就要重新计算原点坐标,不能单纯按照windows/runner/main.cpp中设置的坐标进行缩放。