gpt4 book ai didi

java - 如何绘制更平滑的路径

转载 作者:行者123 更新时间:2023-11-29 05:09:00 24 4
gpt4 key购买 nike

我有一个程序允许用户选择尺寸并绘制自由曲线,类似于图形程序的笔功能。为此,我正在使用 Path2D

我正在寻找一种减少绘制路径锯齿的方法。最初我为这个功能使用了 path.lineTo ,导致左边的锯齿状路径。然后我尝试了 path.curveTo,但这会在路径上产生各种尖锐的区域,如右图所示。

jagged path jagged and pointed path

有没有办法用 Path2D 使曲线平滑?

import ...

public class Test extends JPanel implements MouseListener, MouseMotionListener {
int count, midX, midY, curveX, curveY;
Point startPoint, stopPoint, releasePoint;
Shape pathShape;

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
if (pathShape != null) {
g2.setStroke(new BasicStroke(50));
g2.draw(pathShape);
}
}

@Override
public void mousePressed(MouseEvent ev) {
count = 1;
startPoint = new Point(ev.getPoint());
Path2D.Double path = new Path2D.Double();
pathShape = path;
repaint();
}

@Override
public void mouseReleased(MouseEvent ev) {
releasePoint = new Point(ev.getPoint());
Path2D path = (Path2D) pathShape;
path.moveTo(releasePoint.x,releasePoint.y);
path.closePath();
pathShape = path;
}

// The mouseDragged method where lineTo is used.
@Override
public void mouseDragged(MouseEvent ev) {
stopPoint = ev.getPoint();
Path2D path = (Path2D) pathShape;
path.moveTo(startPoint.x,startPoint.y);
path.lineTo(stopPoint.x,stopPoint.y);
pathShape = path;
startPoint = stopPoint;
repaint();
}

// The mouseDragged method where curveTo is used.
@Override
public void mouseDragged(MouseEvent ev) {
if (count == 2) {
midX = stopPoint.x;
midY = stopPoint.y;
}
if (count++ >= 3) {
curveX = midX;
curveY = midY;
midX = stopPoint.x;
midY = stopPoint.y;
}
stopPoint = ev.getPoint();
Path2D path = (Path2D) pathShape;
path.moveTo(startPoint.x,startPoint.y);
if (count >= 3)
path.curveTo(curveX,curveY,midX,midY,stopPoint.x,stopPoint.y);
else
path.lineTo(stopPoint.x,stopPoint.y);
pathShape = path;
startPoint = stopPoint;
repaint();
}
}

最佳答案

尝试使用

g2.setStroke(new BasicStroke(50, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

代替 g2.setStroke(new BasicStroke(50));

关于java - 如何绘制更平滑的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29358207/

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