Bresenham's line algorithm

4 replies [Last post]
garysims
User offline. Last seen 4 weeks 1 day ago. Offline
Joined: 7 Jan 2010

Here is Bresenham's line algorithm in Lua/Corona if anyone is interested...

A few points:

1) It can probably be optimized, so maybe one of your Lua/Corona developers who eek out an extra bit of performance.

2) It uses display.newCircle and maybe display.newRect would be faster

3) The group llGroup is used to store all the points plotted so they can be deleted when necessary.

1
2
3
4
5
6
local function swap(a,b)
        local temp = b
        b = a
        a = temp
        return a, b
end

1
2
3
4
-- Bresenham's line algorithm
local function drawLine(x0, y0, x1, y1)
        local steep = false
        if math.abs(y1 - y0) > math.abs(x1 - x0) then steep = true end

1
2
3
4
        if steep then
                x0, y0 = swap(x0, y0)
                x1, y1 = swap(x1, y1)
        end             

1
2
3
4
5
 
        if x0 > x1 then
                x0, x1 = swap(x0, x1)
                y0, y1 = swap(y0, y1)
        end

1
2
3
4
5
6
        local deltax = x1 - x0
        local deltay = math.abs(y1 - y0)
        local err = deltax / 2
        local ystep = 0
        local y = y0
        if y0 < y1 then ystep = 1 else ystep = -1 end

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        for x=x0,x1 do
                if steep then 
                        local c = display.newCircle( y, x, 2 )
                        c:setFillColor(0,0,0)
                        llGroup:insert(c)                 
                 else 
                        local c = display.newCircle( x, y, 2 )
                        c:setFillColor(0,0,0)
                        llGroup:insert(c)                 
                 end             
                 err = err - deltay
                 if err < 0 then
                         y = y + ystep
                         err = err + deltax
                 end
        end
end

Thanks,

Gary

Replies

afyzendo
User offline. Last seen 1 year 17 weeks ago. Offline
Joined: 9 Feb 2010

You have to end the code tag and start it again if you want to have an empty line in your code. Took me a while to figure that out.

garysims
User offline. Last seen 4 weeks 1 day ago. Offline
Joined: 7 Jan 2010

afyzendo,

Thanks... I have updated my original post and now the code appears as expected.

Many thanks,

Gary

s.w.powers
User offline. Last seen 1 year 4 weeks ago. Offline
Joined: 16 Mar 2010

One handy thing you can do in lua is swap variables really easily.

a, b = b, a

will perform the swap for you.

Scott

MikeHart
User offline. Last seen 1 week 2 days ago. Offline
Joined: 22 Mar 2010

Thanks for the script. This line algo will become usefull for me in the future!

Viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.