import 'dart:math'; import 'dart:ui'; import 'package:flutter/material.dart';
void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Experiments', theme: new ThemeData( ), home: new Home(), debugShowCheckedModeBanner: false, ); } } class Home extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( elevation: 0.0, title: Text('圆圈转圈动画', style: TextStyle( color: Colors.white, letterSpacing: 1.0 ), ), backgroundColor: Color(0xff2979ff), centerTitle: true, ), body: HomeContent(), ); } } class HomeContent extends StatefulWidget { @override _HomeContentState createState() => _HomeContentState(); } class _HomeContentState extends State<HomeContent> with TickerProviderStateMixin { double percentage = 0.0; double newPercentage = 0.0; AnimationController percentageAnimationController;
@override void initState() { super.initState(); setState(() { percentage = 0.0; }); percentageAnimationController = new AnimationController( vsync: this, duration: new Duration(milliseconds: 1000) ) ..addListener((){ setState(() { percentage = lerpDouble(percentage,newPercentage,percentageAnimationController.value); }); }); } @override Widget build(BuildContext context) { return new Center( child: new Container( height: 200.0, 200.0, child: new CustomPaint( foregroundPainter: new MyPainter( lineColor: Colors.lightBlueAccent, completeColor: Colors.blueAccent, completePercent: percentage, 8.0 ), child: new Padding( padding: const EdgeInsets.all(8.0), child: new RaisedButton( color: Colors.green, splashColor: Colors.transparent, shape: new CircleBorder(), child: new Text("Click"), onPressed: (){ setState(() { percentage = newPercentage; newPercentage += 10; if(newPercentage>100.0){ percentage=0.0; newPercentage=0.0; } percentageAnimationController.forward(from: 0.0); }); }), ), ), ), ); } } class MyPainter extends CustomPainter{ Color lineColor; Color completeColor; double completePercent; double width; MyPainter({this.lineColor, this.completeColor, this.completePercent, this.width}); @override void paint(Canvas canvas, Size size) { Paint line = Paint() ..color = lineColor ..strokeCap = StrokeCap.round ..style = PaintingStyle.stroke ..strokeWidth = width; Paint complete = Paint() ..color = completeColor ..strokeCap = StrokeCap.round ..style = PaintingStyle.stroke ..strokeWidth = width; Offset center = Offset(size.width/2, size.height/2); // 坐标中心 double radius = min(size.width/2, size.height/2); // 半径 canvas.drawCircle(
// 画圆方法 center, radius, line ); double arcAngle = 2*pi*(completePercent / 100); canvas.drawArc( Rect.fromCircle(center: center, radius: radius), -pi/2, // 从正上方开始 arcAngle, false, complete ); } @override bool shouldRepaint(CustomPainter oldDelegate) => false; }
效果: