最近Flutter项目新需求中须要实现圆弧样式,以下图所示:html
画布组件CustomPaint,绘制内容经过painter和foregroundPainter。painter绘制在child以前,foregroundPainter绘制在child以后,所以child内容覆盖在painter上层,foregroundPainter内容覆盖在child上层。前端
CustomPaint(
painter: CanvasPainter(),
foregroundPainter: ForegroundPainter(),
child: Container(
height: 50,
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 5),
),
child: Text("我是CustomPaint的child"),
),
),
复制代码
绘制部分的实现由CustomPainter完成。首先建立一个继承CustomPainter的类对象。git
class DemoPainter extends CustomPainter{
@override
void paint(Canvas canvas, Size size) {
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return null;
}
}
复制代码
1度 = pi / 180,因此起始度数 = 度数 * pi / 180。github
drawArc方法0度位置是在圆点水平位置左侧正方向是顺时针,因此圆弧绘制第一个起始度数参数为-240度(-240 * (pi / 180)),已知0度位置并知道360度位置。-240度位置距离圆点垂直位置下方度数为30,缺口总共度数为60。所以第二个度数参数为 300 * (pi / 180)。canvas
绘制圆弧使用drawArc方法,设置绘制圆形尺寸(圆心,半径)、起始角度、圆弧角度、是否闭合。bash
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint();
paint.style = PaintingStyle.stroke;
paint.strokeWidth = 5;
paint.strokeCap = StrokeCap.round;
paint.color = Colors.white;
canvas.drawArc(
Rect.fromCircle(
center: Offset(size.width / 2, size.height / 2), radius: 70),
-240 * (pi / 180),
300 * (pi / 180),
false,
paint);
paint.strokeWidth = 2;
canvas.drawArc(
Rect.fromCircle(
center: Offset(size.width / 2, size.height / 2), radius: 65),
-240 * (pi / 180),
300 * (pi / 180),
false,
paint);
paint.strokeWidth = 1;
canvas.drawArc(
Rect.fromCircle(
center: Offset(size.width / 2, size.height / 2), radius: 60),
-240 * (pi / 180),
300 * (pi / 180),
false,
paint);
}
复制代码
另外CustomPainter还有child,能够经过Stack将文本内容经过Text居中显示,固然UI中间文本和按钮固然也能够用画布绘制的方式实现,完整画布代码以下:ide
DemoPainter(
painter: CanvasPainter(),
foregroundPainter: ForegroundPainter(),
child: Container(
height: 50,
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 5),
),
child: Stack(
children: <Widget>[
Text("我是CustomPaint的child"),
Center(
child: Text(
"96",
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
)
],
),
),
),
复制代码
最后的最后介绍两个优秀的Flutter图表开源库Syncfusion Flutter Charts、Flutter Charting 。你会惊喜的发现经过画布实现图表功能原来能够这么酷炫。ui