Skip to content

Instantly share code, notes, and snippets.

@crcdng
Last active February 8, 2020 12:56
Show Gist options
  • Save crcdng/3e5b6fb8b6915640184ef2cd5bf69741 to your computer and use it in GitHub Desktop.
Save crcdng/3e5b6fb8b6915640184ef2cd5bf69741 to your computer and use it in GitHub Desktop.
Flutter Animated Canvas Example
// flutter animated canvas example
// by @crcdng
// adapted from https://medium.com/flutter-community/flutter-custom-painter-circular-wave-animation-bdc65c112690 by @divyanshub024
import 'dart:math' as math;
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Animated',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: AnimatedRoute(),
);
}
}
class AnimatedRoute extends StatefulWidget {
@override
_AnimatedRouteState createState() => _AnimatedRouteState();
}
class _AnimatedRouteState extends State<AnimatedRoute>
with SingleTickerProviderStateMixin {
double waveRadius = 0.0;
double waveGap = 20.0;
Animation<double> _animation;
AnimationController controller;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: Duration(milliseconds: 500), vsync: this);
controller.forward();
controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
controller.reset();
} else if (status == AnimationStatus.dismissed) {
controller.forward();
}
});
}
@override
Widget build(BuildContext context) {
_animation = Tween(begin: 0.0, end: waveGap).animate(controller)
..addListener(() {
setState(() {
waveRadius = _animation.value;
});
});
return Scaffold(
body: CustomPaint(
size: Size(double.infinity, double.infinity),
painter: AnimatedPainter(waveRadius, waveGap),
),
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
}
class AnimatedPainter extends CustomPainter {
final double waveRadius, waveGap;
var wavePaint;
AnimatedPainter(this.waveRadius, this.waveGap) {
wavePaint = Paint()
..color = Colors.black
..style = PaintingStyle.stroke
..strokeWidth = 2.0
..isAntiAlias = true;
}
@override
void paint(Canvas canvas, Size size) {
double centerX = size.width / 2.0;
double centerY = size.height / 2.0;
double maxRadius = hypot(centerX, centerY);
var currentRadius = waveRadius;
while (currentRadius < maxRadius) {
// wavePaint
// ..color = Color.fromRGBO(math.Random().nextInt(200),
// math.Random().nextInt(200), math.Random().nextInt(200), 0.4)
// ..strokeWidth = math.Random().nextDouble() * 5.0
// ;
canvas.drawCircle(Offset(centerX, centerY), currentRadius, wavePaint);
currentRadius += waveGap;
}
}
double hypot(double x, double y) {
return math.sqrt(x * x + y * y);
}
@override
bool shouldRepaint(AnimatedPainter oldDelegate) {
return oldDelegate.waveRadius != waveRadius;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment