swing GeneralPath::cubicTo绘制平滑曲线

Java 中可以使用 GeneralPath::cubicTo() 函数绘制如下的平滑曲线

绘制平滑曲线的关键是控制点的计算,sp 为线段的起始点,ep 为线段的终点,c1,c2 为贝塞尔曲线的控制点,其坐标计算如下

下面就用个简单的程序介绍怎么绘制平滑曲线,主要部分为 for 循环里控制点 c1, c2 的计算,注意不能把它们的顺序弄反了哦,否则生成的曲线很奇怪的。

     
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
     
     
import javax.swing.*;
import java.awt.*;
import java.awt.geom.GeneralPath;
public class DrawSmoothCurve extends JPanel {
private Point[] points = {
new Point( 0, 0),
new Point( 100, 100),
new Point( 200, - 100),
new Point( 300, 100),
new Point( 330, - 80),
new Point( 350, - 70)
};
GeneralPath path = new GeneralPath();
public DrawSmoothCurve() {
path.moveTo(points[ 0].x, points[ 0].y);
for ( int i = 0; i < points.length- 1; ++i) {
Point sp = points[i];
Point ep = points[i+ 1];
Point c1 = new Point((sp.x + ep.x)/ 2, sp.y);
Point c2 = new Point((sp.x + ep.x)/ 2, ep.y);
path.curveTo(c1.x, c1.y, c2.x, c2.y, ep.x, ep.y);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke( new BasicStroke( 2));
g2d.translate( 40, 130);
g2d.draw(path);
for ( int i = 0; i < points.length; ++i) {
g2d.setColor(Color.GRAY);
g2d.fillOval(points[i].x- 4, points[i].y- 4, 8, 8);
g2d.setColor(Color.BLACK);
g2d.drawOval(points[i].x- 4, points[i].y- 4, 8, 8);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame( "Smooth Curve");
frame.setContentPane( new DrawSmoothCurve());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize( 420, 280);
frame.setLocationRelativeTo( null);
frame.setVisible( true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值