2010-06-09 149 views
13

有沒有人有在給定線條中間繪製箭頭的算法。我已經搜索谷歌,但沒有找到任何好的實施。在線算法繪製箭頭

P.S.我真的不介意這種語言,但如果它是Java,它會很好,因爲它是我用於此的語言。

在此先感謝。

+0

這是一個箭頭指向一條線的中間?還是從它來?或者是沿着這條線的箭頭? – 2010-06-09 23:58:28

+0

一個沿線。 – nunos 2010-06-10 01:17:01

回答

20

這裏有一個函數在點p處繪製一個箭頭。你可以將它設置到你的線的中點。 dx和dy是線方向,由(x1 - x0,y1 - y0)給出。這會給出一個縮放到行長度的箭頭。如果您希望箭頭始終具有相同的大小,請將此方向標準化。

private static void DrawArrow(Graphics g, Pen pen, Point p, float dx, float dy) 
{ 
    const double cos = 0.866; 
    const double sin = 0.500; 
    PointF end1 = new PointF(
     (float)(p.X + (dx * cos + dy * -sin)), 
     (float)(p.Y + (dx * sin + dy * cos))); 
    PointF end2 = new PointF(
     (float)(p.X + (dx * cos + dy * sin)), 
     (float)(p.Y + (dx * -sin + dy * cos))); 
    g.DrawLine(pen, p, end1); 
    g.DrawLine(pen, p, end2); 
} 
+2

如何調整箭頭的大小?我喜歡根據線條的長度來設置它,但目前我的應用程序中箭頭大小與線條大小的比例不正確。 – renosis 2013-02-01 18:49:23

11

這是一種將箭頭添加到一行的方法。 你只需要給它你的箭頭和尾巴的座標。

private static void drawArrow(int tipX, int tailX, int tipY, int tailY, Graphics2D g) 
{ 
    int arrowLength = 7; //can be adjusted 
    int dx = tipX - tailX; 
    int dy = tipY - tailY; 

    double theta = Math.atan2(dy, dx); 

    double rad = Math.toRadians(35); //35 angle, can be adjusted 
    double x = tipX - arrowLength * Math.cos(theta + rad); 
    double y = tipY - arrowLength * Math.sin(theta + rad); 

    double phi2 = Math.toRadians(-35);//-35 angle, can be adjusted 
    double x2 = tipX - arrowLength * Math.cos(theta + phi2); 
    double y2 = tipY - arrowLength * Math.sin(theta + phi2); 

    int[] arrowYs = new int[3]; 
    arrowYs[0] = tipY; 
    arrowYs[1] = (int) y; 
    arrowYs[2] = (int) y2; 

    int[] arrowXs = new int[3]; 
    arrowXs[0] = tipX; 
    arrowXs[1] = (int) x; 
    arrowXs[2] = (int) x2; 

    g.fillPolygon(arrowXs, arrowYs, 3); 
} 
+0

非常感謝你......你節省了我很多時間...... – 2012-05-03 16:35:43