Java2D支持通过GeneralPath实现绘制任意的几何形状。
步骤:1)实例化GeneralPath对象
2)调用moveTo()方法锚地开始点坐标
3)调用lineTo()或curveTo()方法绘制连接线
4)调用closePath()方法完成几何形状绘制
package chapter1;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.GeneralPath;
public class GeneralPathDemo extends JPanel {
private static final long serialVersionUID = 1L;
public GeneralPathDemo(){
super();
}
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
int x1 = this.getWidth()/5;
int y1 = this.getHeight()-20;
int x2 = this.getWidth()/2;
int y2 = 20;
int x3 = this.getWidth()-20;
int y3 = this.getHeight()-20;
int x4 = 20;
int y4 = this.getHeight()/3;
int x5 = this.getWidth()-20;
int y5 = y4;
int x1points[] = {x1,x2,x3,x4,x5};
int y1points[] = {y1,y2,y3,y4,y5};
g2d.setPaint(Color.RED);
GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,x1points.length);
polygon.moveTo(x1points[0],y1points[0]);
//顺序画下其他点
for(int i=1; i
polygon.lineTo(x1points[i],y1points[i]);
}
polygon.closePath();//调用closePath形成一个封闭几何形状
g2d.draw(polygon);//绘制
g2d.dispose();//释放资源
}
public static void main(String args[]){
JFrame jf = new JFrame("Demo Graphics");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(new GeneralPathDemo(), BorderLayout.CENTER);
jf.setPreferredSize(new Dimension(380, 380));
jf.pack();
jf.setVisible(true);
}
}
如果觉得《java如何画五角星_Java——绘制五角星》对你有帮助,请点赞、收藏,并留下你的观点哦!