gpt4 book ai didi

canvas - JavaFX - 带箭头画线( Canvas )

转载 作者:行者123 更新时间:2023-12-03 23:08:22 25 4
gpt4 key购买 nike

我在将此代码重写为 JavaFX 时遇到问题:

private final int ARR_SIZE = 8;

void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) {
Graphics2D g = (Graphics2D) g1.create();
g.setPaint(Color.BLACK);

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);

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);
}

我的解决方案无法正常工作,因为代码的结果:

drawArrow(gc, 200, 50, 50, 50);

arrow .

预期结果是

arrow2 .

private final int ARR_SIZE = 8;

void drawArrow(GraphicsContext gc, int x1, int y1, int x2, int y2) {

gc.setFill(Color.BLACK);

double dx = x2 - x1, dy = y2 - y1;
double angle = Math.atan2(dy, dx);
int len = (int) Math.sqrt(dx * dx + dy * dy);

Affine affine = new Affine(Affine.translate(x1, y1));
affine.createConcatenation(Affine.rotate(angle, 0, 0));
gc.setTransform(affine);

gc.strokeLine(0, 0, len, 0);
gc.fillPolygon(new double[]{len, len - ARR_SIZE, len - ARR_SIZE, len}, new double[]{0, -ARR_SIZE, ARR_SIZE, 0},
4);

}

你能帮我吗?

最佳答案

造成这种情况的原因有两个:

  1. 按弧度而不是度数旋转:Transform.rotate 需要以度为单位的角度(请参阅 javadoc for Rotate constructor ;Javadoc 中的 Transform.rotate“重定向”),但是Math.atan2返回弧度。
  2. Transform.createConcatenation创建一个新的 Transform,而不是修改现有的 Transform

这段代码应该可以工作:

void drawArrow(GraphicsContext gc, int x1, int y1, int x2, int y2) {
gc.setFill(Color.BLACK);

double dx = x2 - x1, dy = y2 - y1;
double angle = Math.atan2(dy, dx);
int len = (int) Math.sqrt(dx * dx + dy * dy);

Transform transform = Transform.translate(x1, y1);
transform = transform.createConcatenation(Transform.rotate(Math.toDegrees(angle), 0, 0));
gc.setTransform(new Affine(transform));

gc.strokeLine(0, 0, len, 0);
gc.fillPolygon(new double[]{len, len - ARR_SIZE, len - ARR_SIZE, len}, new double[]{0, -ARR_SIZE, ARR_SIZE, 0},
4);
}

关于canvas - JavaFX - 带箭头画线( Canvas ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35751576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com