Corona SDK Lua,如何制作手指 drawing/painting 应用程序?

Corona SDK Lua, How do I make a finger drawing/painting app?

我是 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)

只要鼠标 clicked/held,每次调用 paint 函数时,它所做的一切都会在屏幕上放置一个圆圈。但是,我移动鼠标的速度越快(我使用的是 Corona SDK),圆圈之间的间距就越大,它会中断线条的流动。

我怎样才能改变它,让它画出一条流畅的线条?

根据您的代码,您所做的只是在触发触摸事件时放置一个圆圈(因此 display.newCircle)。 touch event 当您开始触摸屏幕(在模拟器中点击鼠标)、当您在屏幕上移动手指以及当您取消点击或手指离开屏幕时触发。

在您的例子中,您在第一次触摸屏幕的位置、手指移动的位置以及将 finger/mouse 抬离屏幕的位置放置了一个 5 像素大小的圆圈。您的问题出现在手指移动阶段或 event.phase = "moved" 时。发生这种情况是因为您在移动过程中获得的触摸事件数量受到限制,具体取决于您使用的硬件。因此,如果移动足够大,您将在放置的圆圈之间有一些地方,您的触摸事件或您的情况下的函数 paint 由于此限制而未被调用。

如果您只想要一行,一种方法是使用 newLine method instead of the newCircle method. You would have to separate your touch inputs to their different phases, "began", "moved", "ended". During the "began" phase you would initiate your new line. During the "moved" or "ended" phase, you create (using newLine function) or add to your existing line with the 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是一种相对容易学习的语言) .您可以获得数学路径 here, and one source for Corona can be found here.