This site requires JavaScript, please enable it in your browser!
Greenfoot back

Report as inappropriate.

nccb
nccb presents ...

2012/5/24

Line Drawing

This shows how to decide which pixels to fill when drawing a line on the screen. The thin black line is the "true" line, and the scenario provides a zoomed-in view of the pixels (white and orange squares) that are filled or left empty during the line-drawing.

Left-click to set the start point of the line, and right-click to set the end point.

A full explanation of the algorithm is here: http://sinepost.wordpress.com/2012/05/24/drawing-in-a-straight-line/

7108 views / 28 in the last 7 days

2 votes | 0 in the last 7 days

Tags: with-source

open in greenfoot
Your browser does not support the canvas tag.
nccbnccb

2012/7/3

You're right that you can calulcate the angle from the two points. But how would you draw the line from the angle and two points? There are ways to do it, but they tend to either be potentially imprecise (will miss pixels in some circumstances) or slow. If you think you know a way, try implementing it to see if it works.
Your lines seem to be unusually thick o.O Especially when the angle of the line is 45 degrees. There is an incredibly fast (integer arithmatic only!) line drawing algorithm called the Bresenham's line algorithm that might work better in this situation.
Thanks, Builderboy, the Bresenham's line algorithm looks good. Though I do not understand why we need to know how to draw a line in java, since java.awt.graphics makes this easy.
nccbnccb

2012/7/3

The answer to Builderboy2005 and MatheMagician is the same: I used Wu (which gives thick lines) rather than Bresenham because the same algorithm can be used to do things like shooting: http://sinepost.wordpress.com/2012/05/29/robotic-outlaws/ and visibility calculation: http://sinepost.wordpress.com/2012/06/08/lines-of-sight/ the latter of which is used again in the raycasting 3D example: http://sinepost.wordpress.com/2012/06/16/raycasting/ Bresenham is not very suitable for these other purposes because it would let the shot/visibility pass through walls -- not so good!
Thanks.
Very good point! I wonder if it would be cool to have a button you could press to switch between the two algorithms, that was you could see how they differ :D
SPowerSPower

2012/7/8

@MatheMagician It's always good to know how to do something, even if the graphics package already has classes which can do it :)
SPowerSPower

2012/7/20

@nccb Maybe a late question, but why is Bresenhams algorithm not so good at 'lines of sight'?
SPowerSPower

2012/7/20

Forget my last comment :)
SPowerSPower

2012/8/1

@Builderboy2005 You're right: Bresenham has super fast algorithms (including one for a circle!). I've put them in my Fast graphics scenario, do you want to give some feedback?

See all comments

Want to leave a comment? You must first log in.

Who likes this?

nachocab dlanni