local x = SL:GetMetaValue("SCREEN_WIDTH") -- 屏幕宽
local y = SL:GetMetaValue("SCREEN_HEIGHT") -- 屏幕高
local win = GUI:Win_Create("Win_1", x/2, y/2, 1136, 640)
local layout = GUI:Layout_Create(win, "layout",0, 0, x,y, false)
GUI:setAnchorPoint(
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-04-12 16:47:36 |
👁️ 阅读: 7
根据浮生梦老师前端课程内容,你的代码已经基本实现了需求,但有几个地方需要调整:
1. **容器触摸设置冲突**:你同时设置了`layout`为可触摸和吞噬触摸,这会导致点击事件被吞噬而无法触发
2. **背景图片坐标问题**:`Image_bg`的坐标设置需要调整
修改后的代码:
```lua
local x = SL:GetMetaValue("SCREEN_WIDTH") -- 屏幕宽
local y = SL:GetMetaValue("SCREEN_HEIGHT") -- 屏幕高
local win = GUI:Win_Create("Win_1", x/2, y/2, 1136, 640, false, false, true, false, false, false, 1)
local layout = GUI:Layout_Create(win, "layout", 0, 0, x, y, false)
GUI:setAnchorPoint(layout, 0.5, 0.5)
-- 背景和颜色必须一起设置
GUI:Layout_setBackGroundColor(layout, {"#FF0000", "#4169E1"})
GUI:Layout_setBackGroundColorType(layout, 2)
-- 透明度
GUI:Layout_setBackGroundColorOpacity(layout, 150)
-- 关键修改:设置layout不可触摸,让点击事件穿透到Image_bg
GUI:setTouchEnabled(layout, false)
local imgPath = "res/public/bg_hhjm_02.jpg"
local Image_bg = GUI:Image_Create(layout, "Image_bg", 0, 0, imgPath)
GUI:setAnchorPoint(Image_bg, 0.5, 0.5)
GUI:setPosition(Image_bg, x/2, y/2)
GUI:setTouchEnabled(Image_bg, true)
-- 在Image_bg上设置吞噬触摸,这样点击它时就不会穿透到layout
GUI:setSwallowTouches(Image_bg, true)
GUI:addOnClickEvent(Image_bg, function()
SL:print('=========')
end)
```
**修改说明:**
1. `layout`设置为`setTouchEnabled(false)`,让触摸事件穿透
2. `Image_bg`设置为`setSwallowTouches(true)`,点击图片时吞噬触摸事件
3. 调整了`Image_bg`的坐标设置方式,先创建在(0,0),再移动到中心位置
4. 点击事件绑定到`Image_bg`而不是`layout`
这样实现后,点击背景图片会打印信息,而点击容器其他区域不会有反应。
根据浮生梦老师前端课程内容,你的代码已经基本实现了需求,但有几个地方需要调整:
1. **容器触摸设置冲突**:你同时设置了`layout`为可触摸和吞噬触摸,这会导致点击事件被吞噬而无法触发
2. **背景图片坐标问题**:`Image_bg`的坐标设置需要调整
修改后的代码:
```lua
local x = SL:GetMetaValue("SCREEN_WIDTH") -- 屏幕宽
local y = SL:GetMetaValue("SCREEN_HEIGHT") -- 屏幕高
local win = GUI:Win_Create("Win_1", x/2, y/2, 1136, 640, false, false, true, false, false, false, 1)
local layout = GUI:Layout_Create(win, "layout", 0, 0, x, y, false)
GUI:setAnchorPoint(layout, 0.5, 0.5)
-- 背景和颜色必须一起设置
GUI:Layout_setBackGroundColor(layout, {"#FF0000", "#4169E1"})
GUI:Layout_setBackGroundColorType(layout, 2)
-- 透明度
GUI:Layout_setBackGroundColorOpacity(layout, 150)
-- 关键修改:设置layout不可触摸,让点击事件穿透到Image_bg
GUI:setTouchEnabled(layout, false)
local imgPath = "res/public/bg_hhjm_02.jpg"
local Image_bg = GUI:Image_Create(layout, "Image_bg", 0, 0, imgPath)
GUI:setAnchorPoint(Image_bg, 0.5, 0.5)
GUI:setPosition(Image_bg, x/2, y/2)
GUI:setTouchEnabled(Image_bg, true)
-- 在Image_bg上设置吞噬触摸,这样点击它时就不会穿透到layout
GUI:setSwallowTouches(Image_bg, true)
GUI:addOnClickEvent(Image_bg, function()
SL:print('=========')
end)
```
**修改说明:**
1. `layout`设置为`setTouchEnabled(false)`,让触摸事件穿透
2. `Image_bg`设置为`setSwallowTouches(true)`,点击图片时吞噬触摸事件
3. 调整了`Image_bg`的坐标设置方式,先创建在(0,0),再移动到中心位置
4. 点击事件绑定到`Image_bg`而不是`layout`
这样实现后,点击背景图片会打印信息,而点击容器其他区域不会有反应。
← 返回问答库