前言
接上文,本文讲解如何使用 Flutter 绘制饼状图,最终效果如图
在线查看
定义 PieChart & PiePart
第一步定义 PieChart 和 PiePart 类。PieChart 是整个饼状图控件,有 datas 和 legends 两个属性,表示饼图的数据和每部分的标识。
PiePart 表示饼图的一部分,有 color, startAngle, sweepAngle 三个属性,分别表示颜色,起始弧度值,占据圆形的弧度值。PeiChartPainter 类实现了具体的绘制方法。
class PiePart{
double sweepAngle;
final Color color;
final double startAngle;
PiePart(
this.startAngle,
this.sweepAngle,
this.color,
);
}
class PieChart extends StatefulWidget{
final List datas;
final List legends;
const PieChart({
@required this.datas,
@required this.legends,
});
@override
_PieChartState createState() => _PieChartState();
}
class _PieChartState extends State with TickerProviderStateMixin{
double _total = 0.0;
final List _parts = [];
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 300,
height: 300,
child: CustomPaint(
painter: PeiChartPainter(
total: _total,
parts: _parts,
datas: widget.datas,
legends: widget.legends
),
),
),
],
);
}
}
class PeiChartPainter extends CustomPainter{
final double total;
final List datas;
final List parts;
final List legends;
PeiChartPainter({
@required this.total,
@required this.datas,
@required this.parts,
@required this.legends,
});
@override
void paint(Canvas canvas, Size size) {
// TODO
}
@override
bool shouldRepaint(PeiChartPainter oldDelegate) => true;
}
绘制圆框
先绘制图表的圆框,在 PeiChartPainter 上添加 drawCircle 方法,以圆的中心点和圆的半径绘制一个空心圆形。
void drawCircle(Canvas canvas, Size size) {
final sw = size.width;
final sh = size.height;
// 确定圆的半径
final double radius = math.min(sw, sh) / 2;
// 定义中心点