如何在不偏离中心的情况下使圆圈比圆弧更大?

时间:2013-03-26 21:27:43

标签: java geometry

这是我的代码:

import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class fourfans extends JFrame {
public fourfans(){
    setTitle("DrawArcs");
    add(new ArcsPanel());
    add(new ArcsPanel());
    add(new ArcsPanel());
    add(new ArcsPanel());

}

public static void main(String[] args) {
    fourfans frame = new fourfans();
    GridLayout test = new GridLayout(2,2);
    frame.setLayout(test);
    frame.setSize(250 , 300);
    frame.setLocationRelativeTo(null); // center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);


}


}


class ArcsPanel extends JPanel{

protected void paintComponent(Graphics g){
    super.paintComponent(g);

    int xCenter = getWidth() / 2;
    int yCenter = getHeight() / 2;
    int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);

    int x = xCenter - radius;
    int y = yCenter - radius;

    g.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
    g.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
    g.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
    g.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
    g.drawOval(x, y, 2 * radius, 2 * radius);       
}
}

每次我尝试将2 *半径更改为2.1 *半径时,它都不会让我因为这是一个双倍。然后当我输入一个大于弧线的固定数字时,它会使圆圈偏离中心。

1 个答案:

答案 0 :(得分:0)

为什么输入一个大于圆弧的数字会使你的圆圈偏离中心是因为Java让你将左上角插入x,y而不是圆弧/圆弧的原点。因此,如果你让其中一个更大,你必须重新计算它的x和y,例如

int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);
int radiusOval = (int)(Math.min(getWidth(), getHeight()) * 0.4 * 1.05);

int x = xCenter - radius;
int y = yCenter - radius;
int xOval = xCenter - radiusOval;
int yOval = yCenter - radiusOval;

g.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
g.drawOval(xOval, yOval, (int)(2.1 * radius), (int)(2.1 * radius));