2012-05-02 43 views
1

我困在以下问题上; 我有一个矩形(50x40像素可以说,位置:x1,y1)和一个圆形(半径30,positin x2,y2)。现在我想提请他们Java - 在具有静态尺寸的两个对象之间绘制箭头

void drawArrow(Graphics g1, int x1, int y1, int x2, int y2,) { 
//x1 and y1 are coordinates of circle or rectangle 
//x2 and y2 are coordinates of circle or rectangle, to this point is directed the arrow 
Graphics2D g = (Graphics2D) g1.create(); 
double dx=x2-x1; 
double 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); 
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); 
} 

本准则之间的箭头显然只连接矩形和圆形的特定点(在这张照片我在中间http://imageshack.us/photo/my-images/341/arrk.jpg/连接点)。你有什么想法如何实现这样的stg? (http://imageshack.us/photo/my-images/833/arr2u.jpg/)...我的想法是缩短长度并计算新坐标,但我有点挣扎。

//我调用这个函数是这样的:

drawArrow(g,temp.x+radius/2,temp.y+radius/2,temp2.x+width/2,temp2.y+height/2); 

回答

1

最简单的方法是设置剪裁。如果你将你的圆和你的矩形添加到剪裁中,它将不会绘制它。

它不能解决问题或绘制箭头。为了解决这个问题,你需要使用Shape.getBounds(),找出矩形的边界,然后计算出你的圆的角度,并使用三角法在矩形上找到正确的光点