SWT中绘制箭头

  网上找到的代码,基本可用,但是效率和美观不敢保证。(x1, y1)和(x2, y2)分别是线段的两端点坐标。

为直线绘制箭头
 1     private void paintk(GC g, int x1, int y1, int x2, int y2) {
 2         double H = 8// 箭头高度
 3         double L = 4// 底边的一半
 4         int x3 = 0;
 5         int y3 = 0;
 6         int x4 = 0;
 7         int y4 = 0;
 8         double D = Math.abs(Point2D.distance(x1, y1, x2, y2));
 9         if (D <= SystemConstant.DEFAULTRADIUS/2 ){  // 此部分判断无用
10             return;
11         }
12         x2 = (int) (x1+(x2-x1)*(D-10)/D);// -10是为了本程序中使用,会在距离直线一端10像素处开始绘制
13         y2 = (int) (y1+(y2-y1)*(D-10)/D);// -10是为了本程序中使用,会在距离直线一端10像素处开始绘制
14         double awrad = Math.atan(L / H); // 箭头角度
15         double arraow_len = Math.sqrt(L * L + H * H); // 箭头的长度
16         double[] arrXY_1 = rotateVec(x2 - x1, y2 - y1, awrad, true, arraow_len);
17         double[] arrXY_2 = rotateVec(x2 - x1, y2 - y1, -awrad, true, arraow_len);
18         double x_3 = x2 - arrXY_1[0]; // (x3,y3)是第一端点
19         double y_3 = y2 - arrXY_1[1];
20         double x_4 = x2 - arrXY_2[0]; // (x4,y4)是第二端点
21         double y_4 = y2 - arrXY_2[1];
22         Double X3 = new Double(x_3);
23         x3 = X3.intValue();
24         Double Y3 = new Double(y_3);
25         y3 = Y3.intValue();
26         Double X4 = new Double(x_4);
27         x4 = X4.intValue();
28         Double Y4 = new Double(y_4);
29         y4 = Y4.intValue();
30         // g.setColor(SWT.COLOR_WHITE);
31         // 画线
32         g.drawLine(x1, y1, x2, y2);
33         // 画箭头的一半
34         g.drawLine(x2, y2, x3, y3);
35         // 画箭头的另一半
36         g.drawLine(x2, y2, x4, y4);
37     }
38 
39     public double[] rotateVec(int px, int py, double ang, boolean isChLen,
40             double newLen) {
41         double mathstr[] = new double[2];
42         // 矢量旋转函数,参数含义分别是x分量、y分量、旋转角、是否改变长度、新长度
43         double vx = px * Math.cos(ang) - py * Math.sin(ang);
44         double vy = px * Math.sin(ang) + py * Math.cos(ang);
45         if (isChLen) {
46             double d = Math.sqrt(vx * vx + vy * vy);
47             vx = vx / d * newLen;
48             vy = vy / d * newLen;
49             mathstr[0= vx;
50             mathstr[1= vy;
51         }
52         return mathstr;
53     }

 

 

posted @ 2009-12-28 20:19  OurSnippets  阅读(446)  评论(0)    收藏  举报