【问题标题】:Corona SDK - Check if valid image fileCorona SDK - 检查是否有效的图像文件
【发布时间】:2017-08-31 08:44:44
【问题描述】:

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

有时下载会在中间失败或没有正确保存文件。如果我然后尝试使用 display.newImageRect() 显示图像,则会显示警告:警告:脚本/场景/game.lua:98:文件'test.png'不包含有效图像

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

谢谢, fj

【问题讨论】:

    标签: lua download coronasdk file-exists


    【解决方案1】:

    来自 Lua documentation

    本地状态,err = pcall(functionName)

    pcall 函数在保护模式下调用它的第一个参数,因此 它会在函数运行时捕获任何错误。如果没有 错误,pcall 返回 true,加上调用返回的任何值。 否则,它返回 false 以及错误消息。

    您可以在创建图像时使用pcall 函数来捕获错误

    local image
    
    local status, err = pcall( function() image = display.newImage('img.png', 100, 100) end )
    
    if status and image then
        print( 'no errors ' )
          -- no errors  
    else
        print( 'errors ' )
          -- function raised an error: take appropriate actions 
    end
    

    我在下面使用了来自 Corona 的 network.download 的示例 documentation

    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
    )
    

    【讨论】:

    • 谢谢,我试试看!
    • 看起来 PCALL 没有捕捉到丢失图像的错误。如果文件不存在,它不会捕获错误...??
    猜你喜欢
    • 2010-10-27
    • 2020-12-04
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多