如何绘制具有方向和固定长度的线

时间:2016-02-26 10:15:54

标签: java swing awt

当我向它提供2个点和一个角度(对于方向)时,我希望绘制一条线直到屏幕边缘。例如,如果第一个鼠标点是4,4并且下一个鼠标点是6,6,那么从那些点知道该线具有东北方向,那么应该从4,4到结束时绘制一条线。屏幕并通过6,6。注意:在鼠标到达6,6之后,当鼠标仍然在6,6时,应该绘制直到屏幕边缘的线。

enter image description here

此外,这应该在MouseMoved中完成,最好不要点击,这意味着两个鼠标点都是从MouseMoved获得的。我试了整整一天才得到输出但没用。

1 个答案:

答案 0 :(得分:5)

你需要打破你的问题......

首先,您需要能够计算两点之间的角度

double angle = Math.atan2(toY - fromY, toX - fromX);
哇,这很简单(谢谢你Internet

接下来,我们需要能够计算圆半径上的一个点(好吧,这可能听起来很奇怪,但它是我能想到的最简单的解决方案......我知道我可以解决它,谢谢Internet

toX = (int) (Math.round(fromX + (radius * Math.cos(angle))));
toY = (int) (Math.round(fromY + (radius * Math.sin(angle))));

我们要做的是,创建一个如此大的圆圈,使其扩展到可见的框架边界之外,并绘制出我们的线条!简单!

Follow the dots

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Point from;
        private Point clickTo;
        private Point to;

        public TestPane() {
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (to != null) {
                        to = null;
                        clickTo = null;
                        from = null;
                    }
                    if (from != null) {
                        to = e.getPoint();
                        clickTo = new Point(to);
                        double angle = Math.atan2(to.y - from.y, to.x - from.x);
                        int radius = Math.max(getWidth(), getHeight()) * 2;

                        to.x = (int) (Math.round(from.x + (radius * Math.cos(angle))));
                        to.y = (int) (Math.round(from.y + (radius * Math.sin(angle))));
                    } else {
                        from = e.getPoint();
                    }
                    repaint();
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (from != null) {
                g2d.setColor(Color.RED);
                g2d.fillOval(from.x - 4, from.y - 4, 8, 8);

                if (to != null) {
                    g2d.setColor(Color.GREEN);
                    g2d.fillOval(clickTo.x - 4, clickTo.y - 4, 8, 8);

                    g2d.setColor(Color.BLUE);
                    g2d.drawLine(from.x, from.y, to.x, to.y);
                }
            }
            g2d.dispose();
        }

    }

}

使用中心锚点....

MouseMotionListener支持

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Point from;
        private Point clickTo;
        private Point to;

        public TestPane() {
            addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    from = new Point(getWidth() / 2, getHeight() / 2);
                    to = e.getPoint();
                    clickTo = new Point(to);
                    double angle = Math.atan2(to.y - from.y, to.x - from.x);
                    int radius = Math.max(getWidth(), getHeight()) * 2;

                    to.x = (int) (Math.round(from.x + (radius * Math.cos(angle))));
                    to.y = (int) (Math.round(from.y + (radius * Math.sin(angle))));
                    repaint();
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (from != null) {
                g2d.setColor(Color.RED);
                g2d.fillOval(from.x - 4, from.y - 4, 8, 8);

                if (to != null) {
                    g2d.setColor(Color.GREEN);
                    g2d.fillOval(clickTo.x - 4, clickTo.y - 4, 8, 8);

                    g2d.setColor(Color.BLUE);
                    g2d.drawLine(from.x, from.y, to.x, to.y);
                }
            }
            g2d.dispose();
        }

    }

}
  

还有一件小事,我需要线条有一个灵活的长度,我的意思是它应该在屏幕内,因为这是一个矩形,那么宽度和高度将不同,并且具有固定的长度将使问题是因为它会在某些部分很长而在其他部分很短,任何想法?

所以,你需要知道线与矩形的边界碰撞的位置,这基本上归结为线碰撞检测(因为矩形只有四条线)

所以,Internet to the rescue

我稍微采纳了这个想法并制作了一个方法,它采用了RectangleLine2D并返回了发生碰撞点的Point2Dnull如果没有发生碰撞(在这种情况下,我们应该保证碰撞的99.9%)

Shortended

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Point from;
        private Point clickTo;
        private Point to;

        public TestPane() {
            addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    from = new Point(getWidth() / 2, getHeight() / 2);
                    to = e.getPoint();
                    clickTo = new Point(to);
                    double angle = Math.atan2(to.y - from.y, to.x - from.x);
                    int radius = Math.max(getWidth(), getHeight()) * 2;

                    to.x = (int) (Math.round(from.x + (radius * Math.cos(angle))));
                    to.y = (int) (Math.round(from.y + (radius * Math.sin(angle))));
                    repaint();
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        public Point2D getIntersectionPoint(Line2D line1, Line2D line2) {
            if (!line1.intersectsLine(line2)) {
                return null;
            }
            double px = line1.getX1(),
                    py = line1.getY1(),
                    rx = line1.getX2() - px,
                    ry = line1.getY2() - py;
            double qx = line2.getX1(),
                    qy = line2.getY1(),
                    sx = line2.getX2() - qx,
                    sy = line2.getY2() - qy;

            double det = sx * ry - sy * rx;
            if (det == 0) {
                return null;
            } else {
                double z = (sx * (qy - py) + sy * (px - qx)) / det;
                if (z == 0 || z == 1) {
                    return null;  // intersection at end point!
                }
                return new Point2D.Float(
                        (float) (px + z * rx), (float) (py + z * ry));
            }
        } // end intersection line-line

        public Point2D getIntersectionPoint(Line2D line, Rectangle bounds) {
            Point2D top = getIntersectionPoint(line, new Line2D.Double(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y));
            Point2D bottom = getIntersectionPoint(line, new Line2D.Double(bounds.x, bounds.y + bounds.height, bounds.x + bounds.width, bounds.y + bounds.height));
            Point2D left = getIntersectionPoint(line, new Line2D.Double(bounds.x, bounds.y, bounds.x, bounds.y + bounds.height));
            Point2D right = getIntersectionPoint(line, new Line2D.Double(bounds.x + bounds.width, bounds.y, bounds.x + bounds.width, bounds.y + bounds.height));

            return top != null ? top 
                    : bottom != null ? bottom 
                    : left != null ? left
                    : right != null ? right
                    : null;
        } 

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();
            Rectangle bounds = new Rectangle(50, 50, getWidth() - 100, getHeight() - 100);
            g2d.draw(bounds);

            if (from != null) {
                g2d.setColor(Color.RED);
                g2d.fillOval(from.x - 4, from.y - 4, 8, 8);

                if (to != null) {
                    g2d.setColor(Color.GREEN);
                    g2d.fillOval(clickTo.x - 4, clickTo.y - 4, 8, 8);

                    Line2D line = new Line2D.Double(from, to);
                    g2d.setColor(Color.BLUE);
                    g2d.draw(line);

                    Point2D intersectPoint = getIntersectionPoint(line, bounds);

                    g2d.setColor(Color.MAGENTA);
                    g2d.fill(new Ellipse2D.Double(intersectPoint.getX() - 4, intersectPoint.getY() - 4, 8, 8));

                    g2d.draw(new Line2D.Double(from, intersectPoint));
                }
            }
            g2d.dispose();
        }

    }

}

所以,知道你有一个超出组件可见边界的线的投影(这会对你的另一个问题有帮助),并知道线对内边界感兴趣的地方