小菜准备展示一个简单的饼状图,因需要比较简单单一,所以小菜准备自己绘制一个;今天小菜只尝试绘制过程,暂不涉及手势操作;

小菜对于绘制分为三个步骤:
对于两侧不同颜色类别选项卡,仅需要简单设置一下 Container 的 decoration 装饰器即可,只是方便用户查看饼状图分类而已;
return Container(
height: 45, width: 45,
margin: EdgeInsets.symmetric(vertical: 2.5, horizontal: 10),
decoration: BoxDecoration(color: _color, borderRadius: BorderRadius.circular((25.0))),
child: Center(child: Text(_text, style: TextStyle(fontSize: 12, color: Colors.white))));

对于 Canvas 的基本绘制,小菜在之前的博客中有过简单介绍;此次小菜也是使用最基本的 drawArc 绘制扇形拼接为一个完整圆形方式;
注意:在绘制扇形图时需要注意扇形图的起始角度和终止角度,需要累加上一次绘制的扇形图角度;
// 1. 设置画笔
Paint _paint = Paint()..color = Colors.grey
..strokeWidth = 4.0..style = PaintingStyle.fill;
// 2. 获取 ListData 总的数据值
_sumData() {
if (_listData != null) {
for (int i = 0; i < _listData.length; i++) {
_sum += _listData[i].values.first;
}
}
}
// 3. 根据各个子类别数据比例和旋转角度进行不同颜色的扇形图绘制
if (_listData != null) {
for (int i = 0; i < _listData.length; i++) {
startAngle += sweepAngle;
sweepAngle = _listData[i].values.first * 2 * PI / _sum;
canvas.drawArc(_circle, startAngle, sweepAngle, true,
_paint..color = _subPaint(_listData[i].keys.first));
}
}
}

饼状图绘制好之后就是在各自的扇形面积上绘制文字;其中小菜规定,只有扇形图角度大于等于 30 度的时候才会进行文字绘制,如果扇形图角度太小绘制显示效果不佳;
// 1. 绘制文笔属性(颜色,尺寸等)和最大段落宽度
ParagraphBuilder _pb = ParagraphBuilder(ParagraphStyle(
textAlign: TextAlign.left, fontWeight: FontWeight.w600,
fontStyle: FontStyle.normal, fontSize: 14))
..pushStyle(ui.TextStyle(color: Colors.white));
ParagraphConstraints _paragraph = ParagraphConstraints(width: size.width * 0.5);
if (sweepAngle >= PI / 6) {
// 2. 平移坐标系
canvas.translate(size.width * 0.5, size.height * 0.5);
// 3. 设置旋转角度
canvas.rotate(startAngle + sweepAngle * 0.5);
// 4. 文字绘制
Paragraph paragraph = (_pb..addText(_subName)).build()..layout(_paragraph);
canvas.drawParagraph(paragraph, Offset(50.0, 0.0 - paragraph.height * 0.5));
// 5. 恢复旋转角度
canvas.rotate(-startAngle - sweepAngle * 0.5);
// 6. 恢复起始坐标
canvas.translate(-size.width * 0.5, -size.height * 0.5);
}

[ACEPieWidget 案例源码] github.com/ACE-YANGCE/FlutterApp/blob/master/lib/page/ace_pie_page.dart
小菜仅简短的介绍了一下基本饼状图的样式绘制,其功能还不够完善,后续会加入适当的手势操作;如有错误,请多多指导!
来源: 阿策小和尚
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3244/viewspace-2826983/ ,如需转载,请注明出处,否则将追究法律责任。