Java——繪製五角星

來源:互聯網
上載者:User

標籤:raw   幾何   for   imp   line   height   panel   uid   super   

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);
}


}

Java——繪製五角星

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.