Corona SDK Lua,我如何制作手指绘图/绘画应用程序



我是Lua的新手,我已经编写了以下代码。

   display.setStatusBar(display.HiddenStatusBar)
--Create the 'brush'
function paint(event)
    locationX = event.x
    locationY = event.y
    brush = display.newCircle(locationX, locationY, 5)
end
Runtime:addEventListener("touch", paint)

只要单击/按住鼠标,每次调用paint函数时,它都会在屏幕上放置一个圆圈。然而,我移动鼠标的速度越快(我使用的是Corona SDK(,圆圈的间隔就越大,它会中断线条的流动。

我怎么能改变这一点,让它画出一条流畅的线,不间断?

根据您的代码,只要触发触摸事件,您在那里所做的只是放一个圆圈(因此是display.newCircle(。当您开始触摸屏幕时(在模拟器中单击鼠标(,当您在屏幕上移动手指时,以及当您松开或将手指从屏幕上移开时,都会触发触摸事件。

在你的例子中,你在第一次触摸屏幕的地方,手指移动的地方,以及你把手指/鼠标从屏幕上移开的地方,都放了一个5像素大小的圆圈。您的问题出现在手指移动阶段或事件.phase="移动"时。之所以会出现这种情况,是因为您在移动过程中获得的触摸事件数量受到限制,具体取决于您使用的硬件。因此,如果移动足够大,您将在放置的圆圈之间有一些位置,由于此限制,您的触摸事件或函数paint没有被调用。

如果您只想要一行,可以使用newLine方法而不是newCircle方法。你必须将你的触摸输入分为不同的阶段,"开始"、"移动"、"结束"。在"开始"阶段,您将启动新的生产线。在"移动"或"结束"阶段,您可以创建(使用newLine函数(或使用append函数添加到现有行中。

我还没有测试过这个代码,但它可能看起来像这样:

local line                      --variable to hold the line object
local initX                     --initial X coordinate of touch
local initY                     --initial Y coordinate of touch
local lineCreated = false       --Flag to check if line is already created 
--Create the 'brush'
function paint(event)
    locationX = event.x
    locationY = event.y
    if event.phase == "began" then   --first touch
        --Delete previous line (in this case no multiple lines)
        if(line) then
            line:removeSelf()
            line = nil
        end
        --Set initX and initY with current touch location           
        initX = locationX       
        initY = locationY
    elseif event.phase == "moved" then   --during touch movement
        if lineCreated then
            --line has been created, just append to existing line
            line:append(locationX, locationY)
        else
            --Line has not been created
            --Make new line object, set color, and stroke width
            line = display.newLine(initX, initY, locationX, locationY)
            line:setStrokeColor( 0, 0, 1 )
            line.strokeWidth = 5
            --set line created flag to true
            lineCreated = true
        end     
    elseif event.phase == "ended" or event.phase == "cancelled" then --touch lifted
        --append last touch location to the line
        line:append(locationX, locationY)   
    end
    return true
end
Runtime:addEventListener("touch", paint)

这是一条基本线,所以拐角处可能不平滑。为了制作平滑的线条,你需要应用一些更复杂的算法,比如贝塞尔曲线。其他编程语言对此有很多讨论(重要的是算法,当你更熟悉Lua时,你可以很容易地将其用于Corona,Lua是一种相对容易学习的语言(。你可以在这里得到数学路径,Corona的一个来源可以在这里找到。

最新更新