Created
November 7, 2022 22:03
-
-
Save leighajarett/fccb26fc4bca4c08ca37931089a837e7 to your computer and use it in GitHub Desktop.
Flutter canvas example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'package:flutter/material.dart'; | |
| void main() => runApp(const MaterialApp(home: DemoApp())); | |
| class DemoApp extends StatelessWidget { | |
| const DemoApp({super.key}); | |
| @override | |
| Widget build(BuildContext context) => const Scaffold(body: Signature()); | |
| } | |
| class Signature extends StatefulWidget { | |
| const Signature({super.key}); | |
| @override | |
| State<Signature> createState() => SignatureState(); | |
| } | |
| class SignatureState extends State<Signature> { | |
| List<Offset?> _points = <Offset?>[]; | |
| @override | |
| Widget build(BuildContext context) { | |
| return GestureDetector( | |
| onPanUpdate: (details) { | |
| setState(() { | |
| RenderBox? referenceBox = context.findRenderObject() as RenderBox; | |
| Offset localPosition = | |
| referenceBox.globalToLocal(details.globalPosition); | |
| _points = List.from(_points)..add(localPosition); | |
| }); | |
| }, | |
| onPanEnd: (details) => _points.add(null), | |
| child: | |
| // #docregion CustomPaint | |
| CustomPaint( | |
| painter: SignaturePainter(_points), | |
| size: Size.infinite, | |
| ), | |
| // enddocregion CustomPaint | |
| ); | |
| } | |
| } | |
| // #docregion CustomPaint | |
| class SignaturePainter extends CustomPainter { | |
| SignaturePainter(this.points); | |
| final List<Offset?> points; | |
| @override | |
| void paint(Canvas canvas, Size size) { | |
| final Paint paint = Paint() | |
| ..color = Colors.black | |
| ..strokeCap = StrokeCap.round | |
| ..strokeWidth = 5.0; | |
| for (int i = 0; i < points.length - 1; i++) { | |
| if (points[i] != null && points[i + 1] != null) { | |
| canvas.drawLine(points[i]!, points[i + 1]!, paint); | |
| } | |
| } | |
| } | |
| @override | |
| bool shouldRepaint(SignaturePainter oldDelegate) => | |
| oldDelegate.points != points; | |
| } | |
| // #enddocregion CustomPaint |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment