图片无法卸载 - 请协助解决。

我这里有一些代码,当点击图片(作为我的按钮)时,会随机出现一张新图片。这归功于我创建的一个带有一些图片的表格。

local animalPic

local button = display.newImageRect ("images/animalBtn.jpg", 200, 200)
button.x = 250
button.y = 50

local myPics = {"images/animal1.png", "images/animal2.png"}

function button:tap (event)

    local idx = math.random(#myPics)
    local img = myPics[idx]
    local animalPic = display.newImage(img)
    animalPic.x = contentCenterX
    animalPic.y = contentCenterY
end

button:addEventListener ("tap", button)

问题在于,当我点击按钮时,图形会继续堆积。正确的行为应该是 -

点击按钮后会显示一张图片,同时删除之前的图片。我该如何实现这个行为?我已经尝试了 removeSelf 命令,但它并没有起作用......任何帮助都将不胜感激。

点赞
用户1412855
用户1412855

当您调用 display.newImage() 时,您正在添加新图像。问题是需要删除/隐藏原始图像。也许您真的需要两个对象 - 一个用于当前图像,另一个用于点击事件。当点击事件发生时,隐藏旧图像并显示新图像。另一种选择是将所有图像加载到它们自己的 imageRect 中,然后切换它们的开关。

2014-04-22 20:29:05
用户1925928
用户1925928

每次进入函数时,您都会声明animalPic。您应该先声明它,然​​后将其删除并替换为另一个。

应该是这样的:

local animalPic

function button:tap (event)
    local idx = math.random(#myPics)
    local img = myPics[idx]
    animalPic:removeSelf()
    animalPic = nil
    animalPic = display.newImage(img)
    animalPic.x = contentCenterX
    animalPic.y = contentCenterY
end
2014-04-23 13:36:06