Flutter:教你用CustomPaint画一个自定义的CircleProgressBar
import 'package:flutter/material.dart';
class CircleProgressBar extends CustomPainter {
final double progress;
final Color progressColor;
final double strokeWidth;
CircleProgressBar(this.progress, this.progressColor, this.strokeWidth);
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()
..color = progressColor
..strokeWidth = strokeWidth
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke;
final double progressAngle = 2 * math.pi * (progress / 100);
final Rect rect = Offset.zero & size;
final double radius = math.min(size.width / 2, size.height / 2);
canvas.drawArc(rect.deflate(strokeWidth / 2), -math.pi / 2, progressAngle, false, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
class CircleProgressBarExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SizedBox.fromSize(
size: Size.square(100),
child: CustomPaint(
painter: CircleProgressBar(60, Colors.blue, 5),
),
),
),
);
}
}
这段代码定义了一个CircleProgressBar
类,它继承自CustomPainter
,用于绘制一个圆形进度条。在paint
方法中,我们设置了绘制时用的Paint
对象,并计算了进度对应的弧度。然后我们在提供的Canvas
上绘制了一个弧形。在CircleProgressBarExample
类中,我们创建了一个CustomPaint
Widget,并将CircleProgressBar
作为painter
传入,以展示进度条的实际使用方法。
评论已关闭