我有一个程序,允许用户选择大小并绘制自由曲线,类似于图形程序的笔功能。我正在使用Path2D
。
我正在寻找一种让绘制的路径不那么锯齿的方法。最初我使用了path.lineTo
这个函数,导致左边的锯齿状路径。然后我尝试path.curveTo
,但是这会产生沿着路径的各种尖锐区域,如右图所示。
有没有办法让曲线平滑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();
}
}
答案 0 :(得分:3)
尝试使用
g2.setStroke(new BasicStroke(50, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
而不是g2.setStroke(new BasicStroke(50));