2013-10-15 23 views
18

我開發了一個電信應用程序,用於定位來自塔的信號強度。我已經使用了java swing,並且在移動信號發射器塔位置的給定點周圍繪製圓時出現問題。我已經計算了X,Y座標以及半徑值。如何用給定的X和Y座標繪製一個圓作爲圓的中間點?

請找到下面的代碼,我用它來畫圓,它有問題。

JPanel panelBgImg = new JPanel() { 
    public void paintComponent(Graphics g) { 
     g.drawOval(X, Y, r, r); 
    } 
} 

問題是,它會創建圓,但它不會以X和Y座標爲中心點。它將X和Y座標作爲圓的左上角。

任何人都可以請幫助我通過給定的X和Y座標作爲圓的中心點繪製圓。

回答

33

fillOval適合橢圓內的矩形,with width=r, height = r你得到一個圓圈。 如果你想fillOval(x,y,r,r)繪製一箇中心在(x,y)的圓,你將不得不將矩形移動一半寬度和一半高度。

public void drawCenteredCircle(Graphics2D g, int x, int y, int r) { 
    x = x-(r/2); 
    y = y-(r/2); 
    g.fillOval(x,y,r,r); 
} 

這將在x,y

+7

+1,因爲注意到OP使用'r'(半徑)作爲僞'd'(直徑)。文檔中的參數標記爲「w」和「h」。 –

6

g.drawOval(X - r, Y - r, r, r) 

更換你畫線這應該使左上角你的圈子,使中心成爲(X,Y)正確的地方, 至少只要點(X - r,Y - r)具有範圍內的兩個部件。

+1

我敢肯定它的工作原理,即使頂左邊角落超出範圍 – Cruncher

+0

我從來沒有試過在屏幕外畫東西,所以我會聽取你的意見。然而,當然,如果角落在範圍內,它確實有效。 – qaphla

+0

我同意@Cruncher –

0

兩個答案都是不正確繪製中心的圓。應改爲:

x-=r; 
y-=r; 


drawOval(x,y,r*2,r*2); 
0

爲我工作的唯一的事:

g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);  
7

所以我們都在做同樣的工作回家?

奇怪的是,最新的答案是錯誤的。請記住,繪製/ fillOval以高度和寬度爲參數,而不是半徑。因此,要正確繪製和中心用戶提供的x,y了一圈,你會做這樣的事情的半徑值:

public static void drawCircle(Graphics g, int x, int y, int radius) { 

    int diameter = radius * 2; 

    //shift x and y by the radius of the circle in order to correctly center it 
    g.fillOval(x - radius, y - radius, diameter, diameter); 

} 
2
drawCircle(int X, int Y, int Radius, ColorFill, Graphics gObj) 
+4

歡迎來到Stack Overflow!我建議你[參觀](http://stackoverflow.com/tour)。 當給出答案時,最好給出[一些解釋,爲什麼你的答案](http://stackoverflow.com/help/how-to-answer)是一個。 –

0
import java.awt.Color; 
import java.awt.Graphics2D; 
import java.awt.Graphics; 
import javax.swing.JFrame; 

public class Graphiic 
{ 
    public Graphics GClass; 
    public Graphics2D G2D; 
    public void Draw_Circle(JFrame jf,int radius , int xLocation, int yLocation) 
    { 
     GClass = jf.getGraphics(); 
     GClass.setPaintMode(); 
     GClass.setColor(Color.MAGENTA); 
     GClass.fillArc(xLocation, yLocation, radius, radius, 0, 360); 
     GClass.drawLine(100, 100, 200, 200);  
    } 

} 
相關問題