0

我有代码来绘制带有值和随机颜色的饼图。现在我想旋转整个图形,而不是一块馅饼。这是我的代码:

class Slice{

    double value;
    Color color;
    public Slice(double _value){
        this.value = _value;    
    }
    public void setColor(Color _color){
        this.color = _color;

    }
}

class Component extends JComponent implements MouseListener{

    int movx = 0;
    int movy = 0;

    Slice[] slice = {new Slice(5),new Slice(20),new Slice(33),new Slice(55)};
    public Component(){
        addMouseListener(this);
    }

    public void paint(Graphics g){
        Graphics2D g2 = (Graphics2D)g;
        drawPie(g2, getBounds(), slice);

    }
    public void drawPie(Graphics2D g, Rectangle area, Slice[] s){
        double total = 0.0D;
        //calculate total value
        for(int i=0;i<s.length;i++)
            total+=s[i].value;

        double curentValue = 0.0D;
        int startAngle = 0;
        for(int i = 0;i<s.length;i++){
            Random numGen = new Random();
            s[i].setColor(new Color(numGen.nextInt(256), numGen.nextInt(256), numGen.nextInt(256)));
            startAngle = (int)((curentValue*360)/total);
            int arcAngle = (int)((s[i].value*360)/total) ;
            g.setColor(s[i].color);
            g.rotate(30);//row AA
            g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);   

            curentValue+=s[i].value;

        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        movx = e.getX();
        movy = e.getY();
        repaint();
    }

    // unimplemented Mouse methods removed
}

public class PieChart {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame();
        frame.getContentPane().add(new Component());
        frame.setSize(300,200);
        frame.setVisible(true);
    }
}

我在AA行写rotate的时候不能正常工作?你能帮助我吗?如何旋转整个图表?

4

1 回答 1

2

Graphics2D.rotate 的参数以弧度为单位。

http://docs.oracle.com/javase/6/docs/api/java/awt/Graphics2D.html#rotate%28double%29

http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees

如果要旋转整个图表,则应将旋转代码放在 drawPie 方法的开头,而不是放在 for 循环中。

于 2012-11-15T19:45:28.063 回答