Search code examples
pixel

Trying to draw a line between two points(line not straight)


How can I find out what the line's path will be?

I have a pixel in (30, 20) and want to connect it to the pixel in (37 , 77) how do I go about do that?

in the shortest line possible or atleast a line that makes it look like it's the straightest there is

NOTE: The two pixels don't have any obstacles between them, is it fine to just use a shortest path finding algorithm? and if yes, which one should I use if there are no obstacles?


Solution

  • The classic answer to this is to use Bresenham's line algorithm. The way it works is that you start drawing a straight line in one direction (either up, down, left, or right) basically just incrementing or decrementing either X or Y on your point. But each time, you have to run a quick calculation to see if you need to increment (or decrement) the other value too.