1

My objective is to draw lines and store the x and y coordinates of all the pixels that have been colored so far. I am achieving this by maintaining a 2D array

int graph[][] = new int[1000][1000]  //assuming that the applet 
                                     //window is limited to 1000px X 1000px

Say I want to draw a line from (x1,y1) to (x2,y2). I achieve that by using the drawLine() method as

g.drawLine(x1,y1,x2,y2);  //g is a Graphics object

This will result in a line between the given coordinates. I want to mark every pixel colored as a result of this in my graph matrix. So if (xk,yk) is colored, I would do

graph[xk][yk] = 1;

Using the fact that for every one pixel increment in x, I can get the correspoding change in y (by using the slope of the line), I did

int d = (y2-y1)/(x2-x1);
for(int i=x1;i<x2;i++)
{
    graph[x1][y1]=1;
    g.drawLine(x1,y1,x1++,y1+=d);
}

The obvious problem that I encountered was when dealing with floating point slopes. Every time the slope has a fractional part, it simply truncates the number and draws a line with an integral value slope. The result is that it draws lines that are not smooth with breaks in between.

I cannot make d to be double/float because I cannot increment y1 by floating point values as it is a pixel number.

I am very new to Graphics and Applets, so this^ is the best that I could think of to get what I wanted. I'd be happy to provide any further explanations if needed.

Spektre
  • 49,595
  • 11
  • 110
  • 380
Eulerian
  • 382
  • 2
  • 8
  • You could use `Line2D` and the use it's `PathIterator`. It's more complex, but solves having to do a bunch of maths – MadProgrammer Oct 14 '18 at 06:39
  • see [How can you find the coordinates between two given points on a straight line(JavaScript)?](https://stackoverflow.com/a/52735199/2521214) – Spektre Oct 14 '18 at 10:14
  • 1
    If the objective is **"store the x and y coordinates of all the pixels that have been colored"** consider storing the image as `BufferedImage` and use `BufferedImage.getRGB(x,y)` to scan the entire picture to get the color of each pixel. If you want it "black and white" you need to apply a threshold. – c0der Oct 14 '18 at 12:27

0 Answers0