[Haskell-cafe] Line drawing algorithm
CK Kashyap
ck_kashyap at yahoo.com
Fri Jul 17 08:41:26 EDT 2009
Hi All,
I am working on a diagraming utility in Haskell. I started with line drawing.
I am doing the basic stuff using the y = mx + c formula to draw a line between (x1,y1) and (x2,y2)
Here's what I need to do -
if dx > dy where dx = (x2 - x1) and dy = (y2 - y1) then I need to vary x between x1 and x2 and find the various y's
however if dy > dx then I need to vary y beteen y1 and y2 and get various x's
In the code below, I've only taken care of the situation where dx > dy - I was thinking if there was a better way to
do it that takes care of the other condition as well without repeating the code.
type Point = (Integer,Integer)
line :: Point -> Point -> [Point] -- get all the points in the line
line p1@(x1,y1) p2@(x2,y2) = line' start end start slope
where
(start,end) = reorderPoints p1 p2
slope = ((fromIntegral (y2-y1)) / (fromIntegral (x2-x1)))
reorderPoints (px1,py1) (px2,py2)
| px1 < px2 = (p1,p2)
| otherwise = (p2,p1)
line' :: Point -> Point -> Point -> Double -> [Point]
line' start@(x1,y1) end@(x2,y2) point@(x3,y3) slope
| x3 == x2 = [end]
| otherwise = [point] ++ line' start end (newX,newY) slope
where
newX = x3 + 1
newY = y1 + round (slope * (fromIntegral (newX - x1)))
hello = line (1,1) (10,10)
Regards,
Kashyap
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090717/f0768a39/attachment.html
More information about the Haskell-Cafe
mailing list