Corona SDK - 检查有效图像文件

我正在使用最新的 Corona SDK 版本。在我的应用程序中,我通过 network.download(...) 从网络上加载图像。如果用户离线,我会加载一个占位符。

有时,下载在中途失败或未正确保存文件。如果我尝试使用 display.newImageRect() 显示图像,则会显示警告:WARNING: scripts/scenes/game.lua:98: file 'test.png' does not contain a valid image

如何捕获此警告并显示占位符?检查 fileExists() 无法捕获损坏的文件。

谢谢, fj

点赞
用户7026995
用户7026995

你可以使用pcall函数来捕捉创建图像时的错误

local image

local status, err = pcall( function() image = display.newImage('img.png', 100, 100) end )

if status and image then
    print( 'no errors ' )
      -- 没有错误
else
    print( 'errors ' )
      -- 函数引发错误:采取适当的措施
end

此外,我还提供了从 Corona 文档 中使用 network.download 的示例:

local function networkListener( event )
    if ( event.isError ) then
        print( "Network error - download failed: ", event.response )
    elseif ( event.phase == "began" ) then
        print( "Progress Phase: began" )
    elseif ( event.phase == "ended" ) then
        print( "Displaying response image file" )
        myImage = display.newImage( event.response.filename, event.response.baseDirectory, 60, 40 )
        myImage.alpha = 0
        transition.to( myImage, { alpha=1.0 } )
    end
end

local params = {}
params.progress = true

network.download(
    "http://docs.coronalabs.com/images/simulator/image-mask-base2.png",
    "GET",
    networkListener,
    params,
    "helloCopy.png",
    system.TemporaryDirectory
)
2017-04-05 19:00:20