[英]How to draw a circle with given X and Y coordinates as the middle spot of the circle?
我开发了一个电信应用程序,用于定位信号塔的信号强度。 我使用过 java swing 并且在围绕移动信号发射塔位置的给定点绘制圆圈时遇到问题。 我已经计算了 X、Y 坐标以及半径值。
请找到我用来绘制圆圈的以下代码,但它有问题。
JPanel panelBgImg = new JPanel() {
public void paintComponent(Graphics g) {
g.drawOval(X, Y, r, r);
}
}
问题是,它创建了圆,但没有以 X 和 Y 坐标为中心点。 它将 X 和 Y 坐标作为圆的左上点。
任何人都可以通过将给定的 X 和 Y 坐标作为圆的中心点来帮助我绘制圆。
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
为中心的圆
所以我们都做同样的家庭作业?
奇怪的是,投票最多的答案是错误的。 请记住,draw/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);
}
用
g.drawOval(X - r, Y - r, r, r)
这应该使您的圆的左上角成为使中心成为(X,Y)
的正确位置,至少只要点(X - r,Y - r)
两个分量都在范围内。
drawCircle(int X, int Y, int Radius, ColorFill, Graphics gObj)
JPanel pnlCircle = new JPanel() {
public void paintComponent(Graphics g) {
int X=100;
int Y=100;
int d=200;
g.drawOval(X, Y, d, d);
}
};
您可以根据需要更改 X、Y 坐标和半径。
两个答案都不正确。 它应该是:
x-=r;
y-=r;
drawOval(x,y,r*2,r*2);
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);
}
}
这将在指定的矩形中绘制一条圆弧。 您可以绘制、半圆、四分之一圆等。
g.drawArc(x - r, y - r, r * 2, r * 2, 0, 360)
唯一对我有用的东西:
g.drawOval((getWidth()-200)/2,(getHeight()-200)/2, 200, 200);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.