简体   繁体   English

在两点之间画一条线

[英]drawing a line between two points

Hi I have 2 points (X1,Y1) and (X2,Y2) how can I draw a line between them?嗨,我有 2 个点(X1,Y1)(X2,Y2)如何在它们之间画一条线? thanks谢谢

In Swing:在摇摆中:

Graphics g;
g.drawLine(X1, Y1, X2, Y2);

IF you are drawing on a JPanel , you will usually put this code in the paintComponent method:如果您在JPanel上绘图,您通常会将此代码放在paintComponent方法中:

@Override
protected void paintComponent(Graphics g) {
    g.drawLine(X1, Y1, X2, Y2);
}

To see all available methods on the Graphics class, see the Javadocs .要查看Graphics类上的所有可用方法,请参阅Javadocs

Take a look at the Graphics.drawLine method.看看Graphics.drawLine方法。

You'll basically need to override some widget (like JPanel) or get a Canvas and in the paint method you do something like:您基本上需要覆盖一些小部件(如 JPanel)或获取 Canvas 并在paint方法中执行以下操作:

graphics.drawLine( p1.x, p1.y, p2.x, p2.y );

For a JFrame, you would add a paint method, which is ran when the JVM is ready to draw on the JFrame, inside of the class that has inherited the JFrame class.对于 JFrame,您将在继承 JFrame 类的类中添加一个绘制方法,该方法在 JVM 准备好在 JFrame 上绘制时运行。 Then, inside of that, you would call the 'drawLine' method of the graphic, as demonstrated (ensure that the "Graphics" class has been imported and replace the X1, Y1, X2, Y2 with the integars of your choice.):然后,在其中,您将调用图形的 'drawLine' 方法,如图所示(确保已导入“Graphics”类并将 X1、Y1、X2、Y2 替换为您选择的整数。):

public void paint(Graphics g) {
    g.drawLine(X1,X2,Y1,Y2);
}

You can also try this:你也可以试试这个:

var draw = function(ctx,x1,y1,x2,y2) {

    ctx.strokeStyle = "Black";
    ctx.lineWidth = 4;
    ctx.beginPath();
    ctx.moveTo(x1,y1);
    ctx.lineTo(x2,y2);
    ctx.stroke();

};


var drawPoints = function(ctx,points) {

    ctx.strokeStyle = "Black";
    ctx.lineWidth = 4;
    for(var i = 0; i<points.length -1;i++){
        draw(ctx,points[i][0],points [i][1],points[i+1][0],points[i+1][1]);
    }

};


var ctx = canvas.getContext("2d")

Now call the function as:现在调用函数:

drawPoints(ctx, points);

You can change the var points array to any points you like.您可以将var points array更改为您喜欢的任何点。

var points = [[50,50],[50,100],[100,100],[100,50]];

This should connect all the points with a black line.这应该用黑线连接所有点。 If you enter three points it makes a triangle, with four, a square and so on.如果你输入三个点,它会形成一个三角形,四个,一个正方形等等。 Please let me know if I made a mistake.如果我犯了错误,请告诉我。

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

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