Java——繪制五角星


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<x1points.length; 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);
}


}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM