从一个点到另一个点绘制拱形

时间:2012-05-31 11:21:47

标签: java swing graphics awt graphics2d

我在垂直线上给出了2个点,(x0,y0)和(x0,y1)我希望用拱形连接这两个点(看起来像一个环 - 或者像圆周的一半 - )在(x0,y0)处开始,在(x0,y1)处结束。

如果连接看起来像一个从开始到结束的箭头,那将是完美的。

所有这些都使用Graphics或其他。

提前致谢!!

3 个答案:

答案 0 :(得分:4)

下面的代码生成此截图,它将在两点之间绘制半圈+最后添加一个箭头:

screemshot

代码:

JFrame frame = new JFrame("Test");
frame.add(new JComponent() {
    Point p1, p2; boolean first;
    {
        p1 = p2 = new Point();
        setPreferredSize(new Dimension(400, 400));
        addMouseListener(new MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent e) {
                if (first) p1 = e.getPoint(); else p2 = e.getPoint();
                first = !first;
                repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.fillRect(p1.x-1, p1.y-1, 3, 3); g.drawString("p1", p1.x, p1.y);   
        g.fillRect(p2.x-1, p2.y-1, 3, 3); g.drawString("p2", p2.x, p2.y);

        double angle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
        int diameter = (int) Math.round(p1.distance(p2));

        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(p1.x, p1.y);
        g2d.rotate(angle);
        g2d.drawArc(0, -diameter/2, diameter, diameter, 0, 180);
        g2d.fill(new Polygon(new int[] {0,10,-10}, new int[] {0,-10,-10}, 3));
    }
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);

答案 1 :(得分:2)

  

我在垂直线上给出了2个点,(x0,y0)和(x0,y1)我希望用拱形连接这两个点(看起来像一个环 - 或者像圆周的一半 - )在(x0,y0)处开始,在(x0,y1)处结束。

答案 2 :(得分:2)

这是一个圆弧画示例:

public class ArcExample extends JComponent
{
    protected void paintComponent ( Graphics g )
    {
        super.paintComponent ( g );

        Graphics2D g2d = ( Graphics2D ) g;
        g2d.setRenderingHint ( RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON );

        g2d.setColor ( Color.RED );
        g2d.drawArc ( 0, 0, getWidth (), getHeight (), 90, -180 );
    }

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

    public static void main ( String[] args )
    {
        JFrame frame = new JFrame ();
        frame.add ( new ArcExample () );
        frame.pack ();
        frame.setLocationRelativeTo ( null );
        frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
        frame.setVisible ( true );
    }
}