遍历背包物品显示物品框内
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-05-05 00:46:07 |
👁️ 阅读: 10
根据浮生梦老师前端课程内容,遍历背包并显示物品框可以这样实现:
```lua
-- 首先创建父界面
local parent = GUI:Win_Create("BagMain", 0, 0, 0, 0, false, false, true, false, false, false, 1)
-- 创建滚动容器用于显示物品列表
local scrollView = GUI:ScrollView_Create(parent, "ScrollView_bag", 100, 100, 500, 400, 1)
GUI:ScrollView_setInnerContainerSize(scrollView, 500, 800) -- 设置内部容器大小
-- 假设背包物品数据
local bagItems = {
{id = 1001, name = "屠龙刀", count = 1},
{id = 1002, name = "圣战戒指", count = 2},
{id = 1003, name = "金创药", count = 10},
-- 更多物品...
}
-- 遍历背包物品并创建物品框
local itemWidth = 55 -- 物品框宽度
local itemHeight = 55 -- 物品框高度
local spacing = 10 -- 间距
local columns = 8 -- 每行显示数量
for i, item in ipairs(bagItems) do
-- 计算位置
local row = math.floor((i - 1) / columns)
local col = (i - 1) % columns
local x = col * (itemWidth + spacing) + spacing
local y = -row * (itemHeight + spacing) - spacing
-- 创建物品框背景
local itemPanel = GUI:Layout_Create(scrollView, "Panel_item_"..i, x, y, itemWidth, itemHeight, false)
GUI:setAnchorPoint(itemPanel, 0, 1) -- 锚点左上角
-- 创建物品背景图
local bgImage = GUI:Image_Create(itemPanel, "Image_bg", itemWidth/2, itemHeight/2, "res/public/1900000651.png")
GUI:setContentSize(bgImage, itemWidth, itemHeight)
GUI:setIgnoreContentAdaptWithSize(bgImage, false)
-- 创建物品图标(这里用占位图,实际应该根据item.id获取对应图标)
local itemIcon = GUI:Image_Create(itemPanel, "Image_icon", itemWidth/2, itemHeight/2, "res/public_win32/1900000610.png")
GUI:setContentSize(itemIcon, 40, 40)
-- 创建物品数量文本
if item.count > 1 then
local countText = GUI:Text_Create(itemPanel, "Text_count", itemWidth-5, 5, 12, "#ffffff", tostring(item.count))
GUI:setAnchorPoint(countText, 1, 0) -- 锚点右上角
GUI:Text_enableOutline(countText, "#000000", 1)
end
-- 添加点击事件
GUI:addOnClickEvent(itemPanel, function()
SL:print("点击了物品:"..item.name.." ID:"..item.id)
end)
end
-- 根据实际物品数量调整滚动区域高度
local totalRows = math.ceil(#bagItems / columns)
local totalHeight = totalRows * (itemHeight + spacing) + spacing
GUI:ScrollView_setInnerContainerSize(scrollView, 500, totalHeight)
```
**关键函数说明:**
1. `GUI:ScrollView_Create(parent, id, x, y, width, height, direction)` - 创建滚动视图
- `direction = 1` 表示垂直滚动
2. `GUI:ScrollView_setInnerContainerSize(scrollView, width, height)` - 设置内部容器大小
- 需要根据实际内容动态调整高度
3. `GUI:Layout_Create(parent, id, x, y, width, height, clipping)` - 创建布局容器作为物品框
- `clipping = false` 表示不裁剪超出部分
4. `GUI:Image_Create(parent, id, x, y, imagePath)` - 创建图片控件
- 物品图标和背景图都使用这个函数
5. `GUI:setAnchorPoint(widget, x, y)` - 设置锚点
- (0,1)表示左上角,(0.5,0.5)表示中心
**注意事项:**
- 实际物品图标路径需要根据物品ID从配置中获取
- 物品数量显示在右上角,使用白色字体黑色描边
- 每个物品框都有点击事件,可以处理物品使用、查看详情等操作
- 滚动区域高度需要根据物品数量动态计算
这样就能实现一个完整的背包物品遍历显示功能了!
← 返回问答库