Drawing a line with arrow in Java

后端 未结 2 1956
故里飘歌
故里飘歌 2020-12-29 11:06

\"altCan anyone guide me how to code the arrow line in different direction. wa and wl is positive the rectangle

相关标签:
2条回答
  • 2020-12-29 11:40

    Here is a simple routine (adopted from here) for drawing arbitrary arrows:

    import static java.awt.geom.AffineTransform.*;
    import java.awt.*;
    import java.awt.geom.AffineTransform;
    import javax.swing.*;
    
    public class Main {
        public static void main(String args[]) {
            JFrame t = new JFrame();
            t.add(new JComponent() {
    
                private final int ARR_SIZE = 4;
    
                void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) {
                    Graphics2D g = (Graphics2D) g1.create();
    
                    double dx = x2 - x1, dy = y2 - y1;
                    double angle = Math.atan2(dy, dx);
                    int len = (int) Math.sqrt(dx*dx + dy*dy);
                    AffineTransform at = AffineTransform.getTranslateInstance(x1, y1);
                    at.concatenate(AffineTransform.getRotateInstance(angle));
                    g.transform(at);
    
                    // Draw horizontal arrow starting in (0, 0)
                    g.drawLine(0, 0, len, 0);
                    g.fillPolygon(new int[] {len, len-ARR_SIZE, len-ARR_SIZE, len},
                                  new int[] {0, -ARR_SIZE, ARR_SIZE, 0}, 4);
                }
    
                public void paintComponent(Graphics g) {
                    for (int x = 15; x < 200; x += 16)
                        drawArrow(g, x, x, x, 150);
                    drawArrow(g, 30, 300, 300, 190);
                }
            });
    
            t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            t.setSize(400, 400);
            t.setVisible(true);
        }
    }
    

    Result:

    enter image description here

    0 讨论(0)
  • 2020-12-29 11:52

    Simple arrow sample

    /**
     * @param fromPoint end of the arrow
     * @param rotationDeg rotation angle of line
     * @param length arrow length
     * @param wingsAngleDeg wingspan of arrow
     * @return Path2D arrow shape
     */
    public static Path2D createArrowForLine(
                     Point2D fromPoint, 
                     double rotationDeg, 
                     double length, 
                     double wingsAngleDeg) {
    
            double ax = fromPoint.getX();
            double ay = fromPoint.getY();
    
            double radB = Math.toRadians(-rotationDeg + wingsAngleDeg);
            double radC = Math.toRadians(-rotationDeg - wingsAngleDeg);
    
            Path2D resultPath = new Path2D.Double();
            resultPath.moveTo(length * Math.cos(radB) + ax, length * Math.sin(radB) + ay);
            resultPath.lineTo(ax, ay);
            resultPath.lineTo(length * Math.cos(radC) + ax, length * Math.sin(radC) + ay);
            return resultPath;
        }
    
    0 讨论(0)
提交回复
热议问题