简体   繁体   English

在控制台上的两点之间画线

[英]Draw line between two points on console

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 ,...使用DDABresenham ,...

What you have looks like DDA but you do not handle slopes correctly.你所拥有的看起来像DDA ,但你没有正确处理斜坡。 You should divide by the axis with bigger amount of pixels and use it as control axis so:您应该除以具有更多像素的轴并将其用作控制轴,因此:


if |dx|>|dy|如果|dx|>|dy| then for goes through x = x0 -> x1 and y=y0+((x-x0)*dy/dx)然后for通过x = x0 -> x1y=y0+((x-x0)*dy/dx)
if |dx|<|dy|如果|dx|<|dy| then for goes through y = y0 -> y1 and x=x0+((y-y0)*dx/dy)然后for通过y = y0 -> y1x=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如果dx==0dy==0仅绘制点并且不存在for

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不要忘记处理主轴是升序还是降序(可以是x++,y++x--,y-- )也可以仅在整数上完成而无需除法或乘法,但这是另一回事

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM