java - 如何在 Canvas 上用 SWT 画一 strip 箭头的线

标签 java swt awt drawing

我想画一 strip 箭头的线。该线可以有任何角度。如何在SWT中实现它?

我发现了类似的帖子,但它是在 AWT 中。我想将其转换为 SWT。但将以下方法转换为 SWT 时面临问题。特别是在以下行中:

at.concatenate(AffineTransform.getRotateInstance(angle));

这是 this post 中的方法

void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) {
  Graphics2D g = (Graphics2D) g1.create();
  double dx = x2 - x1, 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);

  // Draw horizontal arrow starting in (0, 0)
  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);
}

最佳答案

这里,箭头方向是根据线的方向计算的。我还为该线添加了偏移量,以便它不会穿过箭头。笔画宽度越高,这一点越明显。

public static void drawArrow(GC gc, int x1, int y1, int x2, int y2, double arrowLength, double arrowAngle) {
    double theta = Math.atan2(y2 - y1, x2 - x1);
    double offset = (arrowLength - 2) * Math.cos(arrowAngle);

    gc.drawLine(x1, y1, (int)(x2 - offset * Math.cos(theta)), (int)(y2 - offset * Math.sin(theta)));

    Path path = new Path(gc.getDevice());
    path.moveTo((float)(x2 - arrowLength * Math.cos(theta - arrowAngle)), (float)(y2 - arrowLength * Math.sin(theta - arrowAngle)));
    path.lineTo((float)x2, (float)y2);
    path.lineTo((float)(x2 - arrowLength * Math.cos(theta + arrowAngle)), (float)(y2 - arrowLength * Math.sin(theta + arrowAngle)));
    path.close();

    gc.fillPath(path);

    path.dispose();
}

...

gc.setLineWidth(1);
gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
gc.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
drawArrow(gc, x1, y1, x2, y2, 8, Math.toRadians(40));

关于java - 如何在 Canvas 上用 SWT 画一 strip 箭头的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34159006/

相关文章:

java - 使用 AffineTransform 将 PDFbox 转换为 iText 坐标

java - 使用reviewboard API创建新请求

java - 什么是 <context :spring-configured/>? 的 spring java 配置

java - 当用户单击窗口右上角的 "x"而不是按钮时,加入超时选项。

java - 在 Java 方法中使用标志的最佳实践

java - 如何在SWT中选择用于保存的文件夹?

java - 带有 maven 和无法解析的构建扩展的 Android : Plugin com. jayway.maven.plugins.android.generation2 :android-maven-plugin:3. 9.0-rc.3

java - 在 Gradle 中使用 SWT 无法解决所有依赖项

java - Swing/JFrame 与 AWT/Frame 在 EDT 之外的渲染

java - 将 MouseListener 添加到图形对象