【发布时间】:2016-01-12 10:20:38
【问题描述】:
我想在饼图切片的中间绘制一个带有三角形的饼图。 目前我在切片中间画了一个带有切片和三角形的饼图,但三角形不是直角。我需要知道如何以正确的方式定位三角形。我的代码和结果:
import java.awt.*;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
class Slice {
double value;
Color color;
public Slice(double value, Color color) {
this.value = value;
this.color = color;
}
}
class PieChart extends JPanel {
private Color a = Color.RED;
private Color b = Color.BLUE;
private Color c = Color.YELLOW;
Slice[] slices = {
new Slice(60, a),
new Slice(100, b),
new Slice(200, c)
};
public PieChart(){
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
super.paintComponent(g2d);
this.setBackground(new Color(255,255,255));
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
double total = 0.0D;
for (int i = 0; i < slices.length; i++) {
total += slices[i].value;
}
double curValue = 90.0D;
int startAngle = 0;
for (int i = 0; i < slices.length; i++) {
startAngle = (int) (curValue * 360 / total);
int arcAngle = (int) (slices[i].value * 360 / total);
g2d.setColor(slices[i].color);
g2d.fillArc(20, 20, 200, 200, startAngle, arcAngle);
g2d.setPaint(Color.BLACK);
int x = (int)(110+100*Math.cos(((-(startAngle+(arcAngle/2)))*Math.PI)/180));
int y = (int)(110+100*Math.sin(((-(startAngle+(arcAngle/2)))*Math.PI)/180));
Polygon p = new Polygon(new int[] {x, x+14, x+7}, new int[] {y, y, y-14}, 3); // this values seems to be important
g2d.draw(p);
g2d.fill(p);
curValue += slices[i].value;
}
}
}
编辑:应该是这样的:
【问题讨论】:
-
很高兴看到带有 desired 三角形位置的图片。现在还不太清楚,你想实现什么。
-
如果我没看错,您希望三角形的底边与扇形弧的中心点相切。他们将接触一点。这是正确的吗?
标签: java swing draw pie-chart paintcomponent