怎么跟随分辨率调整 页面在中间
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-04-06 23:53:41 |
👁️ 阅读: 0
要让页面跟随分辨率调整并保持在中间,可以使用以下方法:
## 方法一:使用锚点(Anchor Point)居中
```lua
-- 创建父容器
local parent = GUI:Win_Create("GMMain", 0, 0, 0, 0, false, false, true, false, false, false, 1)
-- 创建需要居中的页面
local centerPanel = GUI:Layout_Create(parent, "centerPanel", 0, 0, 400, 300, false)
GUI:Layout_setBackGroundImageScale9Enabled(centerPanel, true)
-- 设置锚点为中间(0.5, 0.5)
GUI:setAnchorPoint(centerPanel, 0.5, 0.5)
-- 获取屏幕分辨率
local screenWidth = SL:GetMetaValue("SCREEN_WIDTH", 0)
local screenHeight = SL:GetMetaValue("SCREEN_HEIGHT", 0)
-- 设置位置到屏幕中心
GUI:setPosition(centerPanel, screenWidth / 2, screenHeight / 2)
```
## 方法二:使用相对布局
```lua
-- 创建页面容器
local mainPanel = GUI:Layout_Create(parent, "mainPanel", 0, 0, 0, 0, false)
GUI:Layout_setBackGroundImageScale9Enabled(mainPanel, true)
-- 创建居中内容
local content = GUI:Layout_Create(mainPanel, "content", 0, 0, 400, 300, false)
GUI:Layout_setBackGroundImageScale9Enabled(content, true)
-- 设置内容在父容器中居中
GUI:setAnchorPoint(content, 0.5, 0.5)
GUI:setPosition(content, 0, 0) -- 相对父容器的中心
-- 监听分辨率变化
local function onResolutionChange()
local screenWidth = SL:GetMetaValue("SCREEN_WIDTH", 0)
local screenHeight = SL:GetMetaValue("SCREEN_HEIGHT", 0)
-- 调整父容器大小
GUI:setContentSize(mainPanel, screenWidth, screenHeight)
-- 居中内容会自动跟随
end
```
## 方法三:使用百分比位置(推荐)
```lua
-- 创建居中页面
local centerWindow = GUI:Layout_Create(parent, "centerWindow", 0, 0, 400, 300, false)
GUI:Layout_setBackGroundImageScale9Enabled(centerWindow, true)
-- 设置位置为屏幕中心
local function updateCenterPosition()
local screenWidth = SL:GetMetaValue("SCREEN_WIDTH", 0)
local screenHeight = SL:GetMetaValue("SCREEN_HEIGHT", 0)
local windowWidth = 400
local windowHeight = 300
-- 计算居中位置
local centerX = (screenWidth - windowWidth) / 2
local centerY = (screenHeight - windowHeight) / 2
GUI:setPosition(centerWindow, centerX, centerY)
end
-- 初始设置
updateCenterPosition()
-- 可以添加分辨率变化的监听
-- 注意:996引擎中可能需要通过事件监听分辨率变化
```
## 关键技巧:
1. **锚点设置**:`GUI:setAnchorPoint(widget, 0.5, 0.5)` 设置锚点为中间
2. **获取分辨率**:使用 `SL:GetMetaValue("SCREEN_WIDTH", 0)` 和 `SL:GetMetaValue("SCREEN_HEIGHT", 0)`
3. **位置计算**:中心位置 = (屏幕尺寸 - 控件尺寸) / 2
4. **动态调整**:在分辨率变化时重新计算位置
## 完整示例:
```lua
-- 创建背景
local background = GUI:Layout_Create(parent, "background", 0, 0, 0, 0, false)
GUI:Layout_setBackGroundImage(background, "res/public_win32/1900000610.png", 0)
-- 创建居中按钮
local centerButton = GUI:Button_Create(background, "centerButton", 0, 0, "res/public_win32/1900000612.png")
GUI:Button_setTitleText(centerButton, "居中按钮")
-- 设置居中
local function centerWidget(widget)
if GUI:Win_IsNull(widget) then return end
local screenWidth = SL:GetMetaValue("SCREEN_WIDTH", 0)
local screenHeight = SL:GetMetaValue("SCREEN_HEIGHT", 0)
local widgetSize = GUI:getContentSize(widget)
local centerX = (screenWidth - widgetSize.width) / 2
local centerY = (screenHeight - widgetSize.height) / 2
GUI:setPosition(widget, centerX, centerY)
end
-- 应用居中
centerWidget(centerButton)
```
这样页面就会始终保持在屏幕中央,无论分辨率如何变化。
← 返回问答库