我想绘制一个三角形,其顶点在Java Swing中有点平滑.我学会了如何使用这些代码行绘制三角形
Polygon p=new Polygon (vertice_x, vertices_y, number_of_vertices);
g.drawPolygon(p);
但我没有发现圆角.我读过Graphics2D中有一个方法可以让你绘制一个带圆角边框的矩形,但是对于一般的Polygon?我该怎么办?
解决方法:
为了更好地控制圆角(超过使用Stroke),您可以组合3条边线,3条贝塞尔曲线用于圆角.使用线性插值来获取直线和曲线的起点/终点,角点是曲线的控制点.
public Point interpolate(Point p1, Point p2, double t){
return new Point((int)Math.round(p1.x * (1-t) + p2.x*t),
(int)Math.round(p1.y * (1-t) + p2.y*t));
}
Point p1 = new Point(50,10);
Point p2 = new Point(10,100);
Point p3 = new Point(100,100);
Point p1p2a = interpolate(p1, p2, 0.2);
Point p1p2b = interpolate(p1, p2, 0.8);
Point p2p3a = interpolate(p2, p3, 0.2);
Point p2p3b = interpolate(p2, p3, 0.8);
Point p3p1a = interpolate(p3, p1, 0.2);
Point p3p1b = interpolate(p3, p1, 0.8);
...
g.drawLine(p1p2a.x, p1p2a.y, p1p2b.x, p1p2b.y);
g.drawLine(p2p3a.x, p2p3a.y, p2p3b.x, p2p3b.y);
g.drawLine(p3p1a.x, p3p1a.y, p3p1b.x, p3p1b.y);
QuadCurve2D c1 = new QuadCurve2D.Double(p1p2b.x, p1p2b.y, p2.x, p2.y, p2p3a.x, p2p3a.y);
QuadCurve2D c2 = new QuadCurve2D.Double(p2p3b.x, p2p3b.y, p3.x, p3.y, p3p1a.x, p3p1a.y);
QuadCurve2D c3 = new QuadCurve2D.Double(p3p1b.x, p3p1b.y, p1.x, p1.y, p1p2a.x, p1p2a.y);
g.draw(c1);
g.draw(c2);
g.draw(c3);
在上面的代码中,您可以调整传递给interpolate的t参数以更改角的舍入方式.
您还可以将所有这些附加到Path2D.Path2D实现Shape接口,其中允许将对象传递给Graphics2D.fill以填充Shape
Path2D path = new Path2D.Double();
AffineTransform at = new AffineTransform();
path.moveTo(p1p2a.x, p1p2a.y);
path.lineTo(p1p2b.x, p1p2b.y);
path.append(c1.getPathIterator(at), true);
path.lineTo(p2p3b.x, p2p3b.y);
path.append(c2.getPathIterator(at), true);
path.lineTo(p3p1b.x, p3p1b.y);
path.append(c3.getPathIterator(at), true);
path.closePath();
g.fill(path);
标签:java,polygon,swing,rounded-corners
来源: https://codeday.me/bug/20190724/1527793.html