How can I draw a line on the console if I have a 2D array of chars. The function I want to write is something like:
This is my first attempt, but it looks totally wrong
public static void line(char[][] mPixels, int startRow, int startColumn, int endRow, int endColumn)
{
double dY = endRow - startRow;
double dX = endColumn - startColumn;
double slope = dX / dY;
slope = Math.abs(slope);
if(slope >= 1)
{
double progress = -(dY / dX);
for(int i=startColumn; i<=endColumn; i++)
{
double j = startRow - (int) ((i-startColumn) * progress);
int yLoc = (int) (Math.round( j * 100.0 ) / 100.0);
mPixels[i][yLoc] = '*';
}
}
// print array
}
use DDA or Bresenham,...
What you have looks like DDA but you do not handle slopes correctly. You should divide by the axis with bigger amount of pixels and use it as control axis so:
if |dx|>|dy|
then for
goes through x = x0 -> x1
and y=y0+((x-x0)*dy/dx)
if |dx|<|dy|
then for
goes through y = y0 -> y1
and x=x0+((y-y0)*dx/dy)
if they are equal then use any of above.
if dx==0
and dy==0
draw just dot and no for
is present
Do not forget to handle if main axis is ascending or descending (can be x++,y++
or x--,y--
) also can be done on integer only without division or multiplication but that is another story