我有代码可以绘制带有值和随机颜色的饼图。现在我想旋转整个图形,而不是一 block 饼。这是我的代码:
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
时,无法正常工作?你能帮助我吗?如何旋转整个图表?
最佳答案
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循环中。
关于java - 如何在java中旋转饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13404766/