我想画一 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/