首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建一条头部距离末端一定距离的行- java / awt

如何创建一条头部距离末端一定距离的行- java / awt
EN

Stack Overflow用户
提问于 2019-04-07 07:07:05
回答 1查看 110关注 0票数 1

我有几分

A(x1,y1) B(x2,y2)

我需要画这条线的箭头头,但不要画在末端。一定离终点有一段距离。这东西会怎么做?

我有:

代码语言:javascript
复制
    ---------------------->

我需要:

代码语言:javascript
复制
    ----------------->-----

见图:

这是一个角度:

结果:

谢谢你们的帮助。这是给另一个。

让我们创建主函数并绘制一条直线和箭头:

代码语言:javascript
复制
   private void drawLineWithArrowHead(Point from, Point to, Graphics2D graphics){
       Polygon arrowHead = new Polygon();
       arrowHead.addPoint( 0,6);
       arrowHead.addPoint( -6, -6);
       arrowHead.addPoint( 6,-6);int y1,y2,x1,x2;
       x1=from.getPosX();
       y1=from.getPosY();
       x2=to.getPosX();
       y2=to.getPosY();
       Line2D.Double line = new Line2D.Double(x1,y1,x2,y2);
       graphics.draw(line);

让我们加载旧的仿射变换并从线上获得新的:

代码语言:javascript
复制
   AffineTransform tx, old_tx = graphics.getTransform();
   tx = calcAffineTransformation(line);

一些数学:

代码语言:javascript
复制
   double dx = (x2-x1), dy = (y2-y1);
   double len = Math.sqrt(dx*dx + dy*dy);
   double udx = dx/len, udy = dy/len;
   double cordx = x2  - (size-5) * udx, cordy = y2  - (size-5) * udy;
   double r_cordx = x2  - (size+3) * udx, r_cordy = y2  - (size+3) * udy;

现在把箭头放在:

代码语言:javascript
复制
   tx.setToIdentity(); // null transform to origin
   double angle = Math.atan2(line.y2 - line.y1, line.x2 - line.x1);
   !! important !! must firstly translate secondly rotate
   tx.translate( cordx,  cordy ); // setup of cord of arrowhead
   tx.rotate((angle - Math.PI / 2d)); // head rotate
   graphics.setTransform(tx); // set transform for graphics
   graphics.fill(arrowHead);
   graphics.setTransform(old_tx); // get original transform back

获得直线位置和旋转的CalcAffineTransformation函数:

代码语言:javascript
复制
   private AffineTransform calcAffineTransformation(Line2D.Double line) {
       AffineTransform transformation = new AffineTransform();
       transformation.setToIdentity();
       double angle = Math.atan2(line.y2 - line.y1, line.x2 - line.x1);
       transformation.translate(line.x2, line.y2);
       transformation.rotate((angle - Math.PI / 2d));
       return transformation;
   }

仅此而已。这就是代码所做的:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-07 12:35:55

你的线有方向矢量

代码语言:javascript
复制
 dx, dy = (x2 - x1), (y2 - y1)

它的长度是

代码语言:javascript
复制
 len = sqrt(dx*dx + dy*dy)

单位方向向量

代码语言:javascript
复制
udx, udy = dx/len, dy/len

距终点D点(据我所知,这是箭头的头点):

代码语言:javascript
复制
x3, y3 = x2 - D * udx, y2 - D * udy

你还需要其他东西来建造箭头吗?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55556468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档