[英]How to draw star in java swing using fillPolygon
我在設置星的坐標時遇到問題,有沒有更好的解決方案。 我無法獲得正確的形狀。 有人可以幫我嗎?
public void star(Graphics shapes)
{
shapes.setColor(color);
int[] x = {42,52,72,52,60,40,15,28,9,32,42};
int [] y = {38,62,68,80,105,85,102,75,58,20,38};
shapes.fillPolygon(x, y, 5);
}
老實說,我會使用2D 圖形形狀 API,它們允許您“繪制”一個形狀,這比使用多邊形更簡單(恕我直言)。 優點是,它們易於繪制和變形
話雖如此,您實際遇到的問題是您沒有將正確的信息傳遞給fillPolygon
方法。
如果您查看Graphics#fillPolygon
的JavaDocs ,您會注意到最后一個參數是點數:
nPoints - a 總點數。
但是你正在傳遞5
,你的數組中實際上有11
個點
就像是...
shapes.setColor(color);
int[] x = {42,52,72,52,60,40,15,28,9,32,42};
int [] y = {38,62,68,80,105,85,102,75,58,20,38};
shapes.fillPolygon(x, y, 11);
現在應該繪制所有點,但您的某些坐標略有偏差,因此您可能需要檢查一下
Y 的倒數第二個數字應該是 60 而不是 20
g2.setColor(color);
int[] x = {42,52,72,52,60,40,15,28,9,32,42};
int[] y = {38,62,68,80,105,85,102,75,58,60,38};
g2.fillPolygon(x , y, 11);
一個明星有 10 分,而不是 11 分
setBackground(Color.black);
int[]x={250,150,0,150,100,250,400,350,500,350};
int[]y={100,200,200,300,400,300,400,300,200,200};
g.fillPolygon( (x),(y),10);
setForeground(Color.cyan);
這將有助於繪制黑色背景和青色前景的星星
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.